xml代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="请选择喜欢的水果:" android:textSize="23dp" /> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1"/> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/cb_banana" android:text="香蕉"/> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/cb_apple" android:text="苹果"/> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/cb_snowPear" android:text="雪梨"/> </LinearLayout> <Button android:id="@+id/btn_Submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="提交"/> </LinearLayout>
Activity代码:
public class MainActivity extends AppCompatActivity { private CheckBox cbBanana; private CheckBox cbApple; private CheckBox cbSnowPear; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cbBanana = findViewById(R.id.cb_banana); cbApple = findViewById(R.id.cb_apple); cbSnowPear = findViewById(R.id.cb_snowPear); Button btnSubmit = findViewById(R.id.btn_Submit); btnSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String text =""; if(!cbBanana.isChecked()&&!cbApple.isChecked()&&!cbSnowPear.isChecked()){ Toast.makeText(MainActivity.this,"你未进行选择",Toast.LENGTH_LONG).show(); } else { if(cbBanana.isChecked()){ text+= cbBanana.getText().toString(); } if(cbApple.isChecked()){ text+=cbApple.getText().toString(); } if(cbSnowPear.isChecked()){ text+=cbSnowPear.getText().toString(); } Toast.makeText(MainActivity.this,"你选择了"+text,Toast.LENGTH_LONG).show(); } } }); } }