我們在註冊為某一個網站會員時,以前貌似都要同意一些協議才能註冊成功,在手機應用裡也是一樣的,我們同樣需要簽署一些協議才能進行下一步動作。
下面這個應用是當我們勾選“我同意”後,文字內容會變,同時”確定“按鈕可以點擊,否則”確定“按鈕是不能點擊,也就是說不能進行下一步動作。
實現步驟
一:布局檔案編寫
1.1:布局檔案main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/content"
android:id="@+id/tv"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我同意"
android:id="@+id/checkbox"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="確定"
android:id="@+id/btn1"
/>
</LinearLayout>
二:代碼檔案編寫
2. 1:MainActivity.java
package com.menglin.checkbox;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
public class MianActivity extends Activity
{
//聲明一個Button對象
private Button mybtn = null;
//聲明一個TextView 對象
private TextView mytv = null;
//聲明一個CheckBox 對象
private CheckBox mycheckBox = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//載入main.xml布局檔案
setContentView(R.layout.main);
//以findViewById()方法取得Button對象
mybtn = (Button)findViewById(R.id.btn1);
//以findViewById()方法取得TextView對象
mytv = (TextView)findViewById(R.id.tv);
//以findViewById()方法取得CheckBox對象
mycheckBox = (CheckBox)findViewById(R.id.checkbox);
//給CheckBox對象綁定單擊監聽事件
mycheckBox.setOnClickListener(listener);
//將CheckBox預設設定為未選擇狀態
mycheckBox.setChecked(false);
//將Button預設設定為未啟用狀態
mybtn.setEnabled(false);
}
//監聽事件
private OnClickListener listener = new OnClickListener()
{
@Override
public void onClick(View v)
{
//如果CheckBox選中的話
if(mycheckBox.isChecked())
{
//將Button設定為啟用狀態
mybtn.setEnabled(true);
//設定TextView呈現的內容
mytv.setText("您已完整閱讀該協議並且同意");
}
else
{
//將Button預設設定為未啟用狀態
mybtn.setEnabled(false);
//設定TextView呈現的內容
mytv.setText(R.string.content);
}
}
};
}
三:常量檔案
string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="content">這裡是安卓開發聯盟協議,如果您同意此協議請點擊...</string>
<string name="app_name">CheckBoxDemo</string>
</resources>
運行效果如下