天天看點

控件checkbox和radiobutton和Toast

<b>一、             </b><b>CheckBox</b><b>控件</b>

布局檔案代碼:

&lt;CheckBoxandroid:id="@+id/read"android:text="閱讀"  android:layout_width="fill_parent"

android:layout_height="wrap_content"/&gt;

&lt;CheckBoxandroid:id="@+id/game"android:text="遊戲"  android:layout_width="fill_parent"

&lt;CheckBoxandroid:id="@+id/movie"android:text="電影"  android:layout_width="fill_parent"

Activity代碼:

//設定監聽器

read=(CheckBox)findViewById(R.id.read);

        read.setOnCheckedChangeListener(<b>new</b> CompoundButton.OnCheckedChangeListener() {           

           <b>public</b> <b>void</b> onCheckedChanged(CompoundButton buttonView, <b>boolean</b> isChecked) {

              // <b>TODO</b> Auto-generated method stub

              <b>if</b>(read.isChecked()){

                  Toast.makeText(CheckDemo.<b>this</b>, "你選擇了:"+read.getText(), Toast.LENGTH_LONG).show();

              }

           }

       });

<b>二、             </b><b>RadioButton</b><b>控件</b>

RadioButton控件必須位于一個RadioGroup内。

布局代碼如下:

&lt;RadioGroupandroid:id="@+id/rg" 

android:layout_width="fill_parent"

android:layout_height="wrap_content"

&gt; 

&lt;RadioButtonandroid:id="@+id/nan"android:text="男"android:layout_width="fill_parent"

&lt;RadioButtonandroid:id="@+id/nv"android:text="女"android:layout_width="fill_parent"

&lt;/RadioGroup&gt;

Activity代碼如下:

rg=(RadioGroup)findViewById(R.id.rg);

        rg.setOnCheckedChangeListener(<b>new</b> RadioGroup.OnCheckedChangeListener() {        

           <b>public</b> <b>void</b> onCheckedChanged(RadioGroup group, <b>int</b> checkedId) {

              <b>if</b>(nan.getId()==checkedId){

                  Toast.makeText(CheckDemo.<b>this</b>, "你選擇了:"+nan.getText().toString(), Toast.LENGTH_SHORT).show();

              <b>if</b>(nv.getId()==checkedId){

                  Toast.makeText(CheckDemo.<b>this</b>, "你選擇了:"+nv.getText().toString(), Toast.LENGTH_SHORT).show();

<b>三、             </b><b>Toast</b><b>的用法</b>

Toast.makeText(context,stringInfo,Toast. LISTEN_LONG).show();

Context指明了目前上下文,一般是目前activity的類