RadioGroup、Checkbox、Toast 素颜马尾好姑娘i 2024-02-18 18:56 34阅读 0赞 ### ![Center][] ### **layout文件:** <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" 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=".MainActivity" > <TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Type here:" /> <RadioGroup android:id="@+id/genderGroup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/label" android:orientation="horizontal" > <RadioButton android:id="@+id/femaleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="female" android:button="@null" android:drawableRight="@android:drawable/btn_radio" /> <!-- 选定按钮放在右侧 --> <RadioButton android:id="@+id/maleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="male" /> </RadioGroup> <CheckBox android:id="@+id/swim" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="swim" android:layout_below="@id/genderGroup" android:layout_alignParentRight="true" /> <CheckBox android:id="@+id/run" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="run" android:layout_toLeftOf="@id/swim" android:layout_alignTop="@id/swim" /> </RelativeLayout> **为radioGroup和checkbox添加监听器:** protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); genderGroup = (RadioGroup) findViewById(R.id.genderGroup); genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup rg, int chId) { // -----Toast的用法 Toast.makeText(MainActivity.this, "female", Toast.LENGTH_SHORT).show(); } }); ((CheckBox)findViewById(R.id.run)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) { System.out.println(arg1); } }); } [Center]: https://image.dandelioncloud.cn/pgy_files/images/2024/01/29/d4d1e929ce7448dd86129ffdf784b10e.png
还没有评论,来说两句吧...