对于Button是否允许按钮,需引入android:enabled,当属性值为rue时,则允许点击按钮;当属性值为false时,则禁止按钮点击。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/btn_enable" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="启用测试按钮" /> <Button android:id="@+id/btn_disable" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="禁用测试按钮" /> </LinearLayout> <Button android:id="@+id/btn_test" android:layout_width="match_parent" android:layout_height="wrap_content" android:enabled="false" android:text="测试按钮" android:textColor="#888888" android:textSize="17sp" /> <TextView android:id="@+id/tv_result" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingLeft="5dp" android:text="这里查看测试按钮的点击结果" /> </LinearLayout>
findViewById(R.id.btn_enable).setOnClickListener(this); findViewById(R.id.btn_disable).setOnClickListener(this); tv_result = findViewById(R.id.tv_result); btn_test = findViewById(R.id.btn_test); btn_test.setOnClickListener(this); } @Override public void onClick(View v) { if (v.getId() == R.id.btn_enable) { btn_test.setEnabled(true); // 启用当前控件 } else if (v.getId() == R.id.btn_disable) { btn_test.setEnabled(false); // 禁用当前控件 } else if (v.getId() == R.id.btn_test) { String desc = String.format("您点击了按钮:%s", ((Button)v).getText()); tv_result.setText(desc); // 设置文本视图的文本内容 } }