1. 程式人生 > >Android 基本控制元件的使用二(註冊許可協議)(CheckBox)

Android 基本控制元件的使用二(註冊許可協議)(CheckBox)

需要注意的是:按鈕部分,在複選框選中之前是顯示不可點選狀態,一旦被選中之後就會變成可點選按鈕。

為複選框設定的監聽為: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);
}





}