btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
/** check given view by assertion or cast as u wish */
if(v instance of Button) {
/** cast */
Button button = (Button) v;
/** we can perform some check up */
if(button.getId() == EXPECTED_ID) {
/** disable view */
button.setEnabled(false)
button.setClickable(false);
}
} else {
/** you can for example find desired view by root view */
Button bt = (Button) v.getRootView().findViewById(R.id.btId);
/*check for button */
if(bt!=null) {
/** disable button view */
...
} else {
/** according to @jeroen-bollen remark
* we made assumption that we expected a view
* of type button here in other any case
*/
throw new IllegalArgumentException("Wrong argument: " +
"View passed to method is not a Button type!");
}
}
}
});
9 回答
你试过这个吗?
更新:感谢Gwen . 几乎忘了可以在XML布局中设置
android:clickable
来确定按钮是否可以点击 .您可以使用android:clickable在活动启动时单击't enable it or disable it in your XML (since your layout is set at runtime), but you can set if it' .
您只需在活动中编写一行代码即可
当你想启用相同的按钮时,只需写入
在Java中,一旦有了按钮的引用:
要启用/禁用按钮,您可以使用以下任一方法:
要么:
由于你想从头开始禁用按钮,你可以使用button.setEnabled(false);在onCreate方法中 . 否则,从XML,您可以直接使用:
所以:
是的,只需使用
<Button android:enabled="false" />
即可在XML中禁用它就我而言,
工作正常,它正在启用和禁用按钮 . 但是一旦按钮状态被禁用,它就不会再次返回到启用状态,尽管它是可点击的 . 我尝试了无效和刷新可绘制状态,但没有运气 .
如果您或任何有类似问题的人,对我有用的是再次设置背景可绘制 . 适用于任何API级别 .
在Kotlin中,如果您使用id引用Button View,则启用/禁用按钮
layout.xml
activity.kt
首先在xml中将按钮设为
android:clickable="false"
然后在你的代码中,在
oncreate()
方法里面设置按钮属性为然后在按钮内单击将代码更改为
WRONG WAY 在听众中使用可变参数!!!
RIGHT WAY:
编辑:回复@ jeroen-bollen
当单击视图时,View类对象将回调方法onClick()作为参数本身发送,因此如果它是 Assertion Error 则不会发生null视图参数,例如当View对象类同时被销毁时(例如)由GC收集或方法因黑客而被篡改
关于 instanceof & null
来自作者的三个字
IF U ASK WHY ?
MOSTLY TO AVOID NullPointerException
更少的代码将节省您的代码中的后续错误跟踪时间,并减少异常的发生 .
consider following example: