Android 中CheckBox的isChecked的使用實例詳解
Android 中CheckBox的isChecked的使用實例詳解
范例說明
所有的網絡服務在User使用之前,都需要簽署同意條款,在手機應用程序、手機游戲的設計經驗中,??匆奀heckBox在同意條款情境的運用,其選取的狀態(tài)有兩種即isChecked=true與isChecked=false。
以下范例將設計一個TextView放入條款文字,在下方配置一個CheckBox Widget作為選取項,通過Button.onClickListener按鈕事件處理,取得User同意條款的狀態(tài)。
當CheckBox.isChecked為true,更改TextView的文字內容為“你已接受同意!!”,當未選取CheckBox時,Button則不可以被選擇的(被Disabled)。
范例程序
src/irdc.ex04_04/EX04_04.java
利用CheckBox.OnClickListener里的事件來判斷Button該不該顯示,其方法就是判斷Button.Enabled的值;在一開始時,默認參數為false,當有單擊CheckBox時,Button參數就修改為true。
/* import程序略 */
public class EX04_04 extends Activity
{
/** Called when the activity is first created. */
/*聲明 TextView、CheckBox、Button對象*/
public TextView myTextView1;
public TextView myTextView2;
public CheckBox myCheckBox;
public Button myButton;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*取得TextView、CheckBox、Button*/
myTextView1 = (TextView) findViewById(R.id.myTextView1);
myTextView2 = (TextView) findViewById(R.id.myTextView2);
myCheckBox = (CheckBox) findViewById(R.id.myCheckBox);
myButton = (Button) findViewById(R.id.myButton);
/*將CheckBox、Button默認為未選擇狀態(tài)*/
myCheckBox.setChecked(false);
myButton.setEnabled(false);
myCheckBox.setOnClickListener(new CheckBox.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(myCheckBox.isChecked())
{
/*設置Button為不能選擇對象*/
myButton.setEnabled(true);
myTextView2.setText("");
}
else
{
/*設置Button為可以選擇對象*/
myButton.setEnabled(false);
myTextView1.setText(R.string.text1);
/*在TextView2里顯示出"請勾選我同意"*/
myTextView2.setText(R.string.no);
}
}
});
myButton.setOnClickListener(new Button.OnClickListener()
{
// 程序略
});
}
}
擴展學習
CheckBox在默認內容為空白時(沒有任何默認的提示文字下),可設置提示User的文字,其調用的方法為CheckBox.setHint()方法;在擴展學習的范例練習,是抓取R.string.hello這個字符串常數,其與默認CheckBox文字的結果是相同的,你不妨試試看。
myTextView1 = (TextView) findViewById(R.id.myTextView1); myTextView2 = (TextView) findViewById(R.id.myTextView2); myCheckBox = (CheckBox) findViewById(R.id.myCheckBox); myButton = (Button) findViewById(R.id.myButton); myCheckBox.setChecked(false); /*利用setHIT抓取strings里面的值*/ CharSequence hint = getString(R.string.hello); myCheckBox.setHint(hint); /*設置文字顏色*/ myCheckBox.setHintTextColor(Color.RED);
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
Android中ScrollView實現滑動距離監(jiān)聽器的方法
ScrollView相信對每位Android開發(fā)者們來說都不陌生,所以這篇文章給大家主要介紹了Android中ScrollView實現滑動距離監(jiān)聽器的方法,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-10-10

