我已经创建了一个包含两个按钮的布局,下一步和上一步。在按钮之间,我生成了一些动态视图。所以当我第一次启动应用程序时,我想禁用“Previous”按钮,因为不会有任何以前的视图。我还想禁用“下一步”按钮时,没有更多的视图显示。有办法禁用按钮吗?


当前回答

在Java中使用setEnabled方法即可。

myButton.setEnabled(false); 

在Kotlin

myButton.enabled = false

其他回答

您只需在活动中编写一行代码

Button btn = (Button) findViewById(R.id.button1);
btn.setEnabled(false);

当你想要启用相同的按钮只需写

Button btn = (Button) findViewById(R.id.button1);
btn.setEnabled(true);

有了Kotlin,

// to disable clicks
myButton.isClickable = false 

// to disable button
myButton.isEnabled = false

// to enable clicks
myButton.isClickable = true 

// to enable button
myButton.isEnabled = true

你不能在你的XML中启用它或禁用它(因为你的布局是在运行时设置的),但你可以设置它是否在android:clickable活动启动时是可点击的。

就我而言,

myButton.setEnabled(false);
myButton.setEnabled(true);

工作正常,它是启用和禁用按钮,因为它应该。但是一旦按钮状态变为禁用,它就再也不会回到启用状态,尽管它是可点击的。我尝试使可绘制状态无效并刷新,但运气不佳。

myButton.invalidate();
myButton.refreshDrawableState();

如果你或任何人有类似的问题,什么工作对我是设置背景绘图再次。适用于任何API级别。

myButton.setEnabled(true);
myButton.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.myButtonDrawable));

在Java中使用setEnabled方法即可。

myButton.setEnabled(false); 

在Kotlin

myButton.enabled = false