需要注意的是:按鈕部分,在複選框選中之前是顯示不可點擊狀態,一旦被選中之後就會變成可點擊按鈕。
爲複選框設置的監聽爲:setOnCheckedChangeListener
實現的方法有兩種:
方法一:在 activity_main.xml 中 <Button /> 中 設置 android:enabled="false"
在 MainActivity.java 中的代碼爲: submit.setEnabled(isCheckd);
方法二:在 MainActivity.java 中 直接判斷,當點了複選框的時候,是點擊的;沒點是不可點擊的
// agree 是複選框的名稱
if(agree.isChecked()){
選中
submit.setEnabled(true);
}else {
submit.setEnabled(false);
}
activity_main.xml
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:text="@string/hello_world"/>
<CheckBox
android:id="@+id/cb_agree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:text="我同意以上協議"/>
<Button
android:id="@+id/btn_sumbit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/cb_agree"
android:layout_below="@+id/cb_agree"
android:enabled="false"
android:text="註冊"/>
</RelativeLayout>
MainActivity.java
package cn.sohpia.andoird;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class MainActivity extends Activity implements OnCheckedChangeListener{
// 聲明控件
private CheckBox agree;
private Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化控件
initViews();
// 爲複選框控件設置監聽
agree.setOnCheckedChangeListener(this);
}
/**
* 初始化控件
*/
private void initViews() {
agree = (CheckBox) findViewById(R.id.cb_agree);
submit = (Button) findViewById(R.id.btn_sumbit);
}
/**
* 爲控件設置監聽
*/
@Override
public void onCheckedChanged(CompoundButton btn, boolean isCheckd) {
// 判斷複選框是否選中
// 如果 在xml 中沒有設置 android:enable=flase:則需要些以下代碼
// if(agree.isChecked()){
// 選中
// submit.setEnabled(true);
// }else {
// submit.setEnabled(false);
//}
submit.setEnabled(isCheckd);
}
}