CheckBox與前面的RadioButton相反它是一個多選按鈕這裏給大家邊寫了一個按鈕希望大家可以喜歡。
我們還是說一說它的一個實現步驟:
1、在我們的佈局文件中定義好我們的佈局
2、在Activity中獲取我們佈局好的控件
3.設置單擊事件的
4、通過ishecked()這麼一個方法來判斷我們CheckBook是否選中選中的話就想我們定義好的字符串中添加數據
5、最後進行一個顯示
-----------------------------------------------------------------------------
佈局文件代碼:
<RelativeLayout xmlns: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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="你爲什麼要學習Android "/>
<CheckBox
android:id="@+id/cb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="工資高"/>
<CheckBox
android:id="@+id/cb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="喜歡3g開發"/>
<CheckBox
android:id="@+id/cb3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="父母要求學的"/>
<Button
android:id="@+id/bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="提交" />
</LinearLayout>
</RelativeLayout>
----------------------------------------------------------------------
Activity中的代碼:
package com.example.checkbox;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends Activity {
//定義一個字符串用來保存數據
private String s;
private CheckBox cb1,cb2,cb3;
private Button bt;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb1=(CheckBox) findViewById(R.id.cb1);
cb2=(CheckBox) findViewById(R.id.cb2);
cb3=(CheckBox) findViewById(R.id.cb3);
bt=(Button) findViewById(R.id.bt);
//設置按鈕的單擊事件
bt.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//通過isChecked()方法進行判斷保存數據到s中
if (!cb1.isChecked()&&!cb2.isChecked()&&!cb3.isChecked()) {
s+="請至少現在一項!";
}
if (cb1.isChecked()) {
s+=cb1.getText()+"\n";
}
if (cb2.isChecked()) {
s+=cb2.getText()+"\n";
}
if (cb3.isChecked()) {
s+=cb3.getText()+"\n";
}
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
s="";
}
});
}
}
心得:
其實大家不要看着代碼好像很多的樣子其實關鍵的代碼就只有紅色的那麼一點,最後s="";是對保存的一個數據進行清空的,這樣我們下次點擊的時候就不會連同上次的數據一起顯示。