我已经创建了一个包含两个按钮的布局,下一步和上一步。在按钮之间,我生成了一些动态视图。所以当我第一次启动应用程序时,我想禁用“Previous”按钮,因为不会有任何以前的视图。我还想禁用“下一步”按钮时,没有更多的视图显示。有办法禁用按钮吗?
当前回答
你不能在你的XML中启用它或禁用它(因为你的布局是在运行时设置的),但你可以设置它是否在android:clickable活动启动时是可点击的。
其他回答
在Java中,一旦你有了按钮的引用:
Button button = (Button) findviewById(R.id.button);
要启用/禁用按钮,您可以使用:
button.setEnabled(false);
button.setEnabled(true);
Or:
button.setClickable(false);
button.setClickable(true);
因为你想从一开始就禁用按钮,你可以使用button. setenabled (false);onCreate方法。 否则,从XML中,你可以直接使用:
android:clickable = "false"
So:
<Button
android:id="@+id/button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/button_text"
android:clickable = "false" />
您只需在活动中编写一行代码
Button btn = (Button) findViewById(R.id.button1);
btn.setEnabled(false);
当你想要启用相同的按钮只需写
Button btn = (Button) findViewById(R.id.button1);
btn.setEnabled(true);
是的,它可以在XML中被禁用 只是用:
<Button
android:enabled="false"
/>
错误的方式在监听器中使用变量而不是参数!!
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btnSend.setClickable(false);
}
});
正确的方式:
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!");
}
}
}
});
编辑: 回复@jeroen-bollen
视图。OnClickListener 当单击视图时调用回调的接口定义。 使用方法定义 onClick(查看v);
当视图被单击时,视图类对象使回调方法onClick()发送作为参数本身,所以空视图参数不应该发生,如果它是一个断言错误,它可能发生,例如,当视图对象类被破坏的同时(例如由GC收集)或方法被篡改由于黑客
关于instanceof & null
JLS / 15.20.2。类型比较操作符实例 在运行时,instanceof操作符的结果为true 如果RelationalExpression的值不为空 并且引用可以转换为ReferenceType 而不引发ClassCastException。 否则结果为假。
来自作者的三个字
如果你问为什么?
主要是避免NullPointerException
更多的代码将节省您在代码中跟踪错误的时间,并减少异常的发生。
考虑下面的例子:
View.OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
btnSend.setClickable(false);
}
});
btnSend.setOnClickListener(listener)
btnCancel.setOnClickListener(listener)
你可以从xml中禁用一个按钮,但那不是动态的。动态禁用按钮的最佳方法是。
myButton.setEnabled(false);
推荐文章
- apk (.apk)和应用程序包(.aab)的区别
- 如何设置超时在改造库?
- Android - SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度
- TextView的字体大小在Android应用程序改变字体大小从本机设置
- 如何模拟Android杀死我的进程
- 禁用EditText闪烁光标
- Android Eclipse -无法找到*.apk
- 设置TextView文本从html格式的字符串资源在XML
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Android加载JS包失败
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的