android中控件Checkbox复选框的使用

来源:互联网 发布:华中地区数据科学会议 编辑:程序博客网 时间:2024/04/28 05:03

在layout的activity_main.xml

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="请选择爱好:" />


    <CheckBox 
        android:id="@+id/eat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="吃饭"
        />
    <CheckBox 
        android:id="@+id/sleep"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="睡觉"
        />
    <CheckBox 
        android:id="@+id/chat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="聊天"
        />
    <CheckBox 
        android:id="@+id/sing"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="唱歌"
        />


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="查看" >
    </Button>


activity_main.java

public class MainActivity extends Activity {private CheckBox eat ;private CheckBox sleep ;private CheckBox chat ;private CheckBox sing ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);eat = (CheckBox) findViewById(R.id.eat) ;sleep = (CheckBox) findViewById(R.id.sleep) ;chat = (CheckBox) findViewById(R.id.chat) ;sing = (CheckBox) findViewById(R.id.sing) ;}public void click(View view){StringBuilder sb = new StringBuilder() ;if(eat.isChecked()){sb.append(eat.getText() + ",") ;}if(sleep.isChecked()){sb.append(sleep.getText() + ",") ;}if(chat.isChecked()){sb.append(chat.getText() + ",") ;}if(sing.isChecked()){sb.append(sing.getText() + ",") ;}if(TextUtils.isEmpty(sb.toString())){Toast.makeText(this, "你没有选择任何爱好", 0).show() ;}else{Toast.makeText(this, "你选择的爱好是:" + sb.substring(0, sb.length()-1), 0).show() ;}}}

0 0