Android---20---CheckBox复选框
MainActivity.java:
import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; 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 implements OnClickListener { private CheckBox basketball,football,baseball,pingpang; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); basketball = (CheckBox) findViewById(R.id.basketball); baseball = (CheckBox) findViewById(R.id.baseball); football = (CheckBox) findViewById(R.id.football); pingpang = (CheckBox) findViewById(R.id.pingpang); button = (Button) findViewById(R.id.button); button.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub String s = ""; boolean flag = false; if (basketball.isChecked()){ s += basketball.getText().toString(); flag = true; } if (baseball.isChecked()){ s += baseball.getText().toString(); flag = true; } if (football.isChecked()){ s += football.getText().toString(); flag = true; } if (pingpang.isChecked()){ s += pingpang.getText().toString(); flag = true; } if (flag == false){ Toast.makeText(MainActivity.this, "没有任何选项", 0).show(); }else { Toast.makeText(MainActivity.this, s, 0).show(); } } }
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" 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="com.example.checkboxdemo2.MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="选择爱好" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <CheckBox android:id="@+id/basketball" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="篮球" /> <CheckBox android:id="@+id/football" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="足球" /> <CheckBox android:id="@+id/baseball" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="网球" /> <CheckBox android:id="@+id/pingpang" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="乒乓球" /> </LinearLayout> <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="确定" /> </LinearLayout>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。