Android第六天

xiaoxiao2021-02-28  87

CheckBox控件

一、CheckBox属性 1.实现多选的控件 2.可设置初始状态是否被选中 android:checked=”true” 二、使用 1.初始化

<CheckBox android:id="@+id/checkBox1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:checked="true" android:text="吃火锅" /> <CheckBox android:id="@+id/checkBox1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:checked="true" android:text="吃烧烤" /> <CheckBox android:id="@+id/checkBox1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:checked="true" android:text="吃鸡" /> private CheckBox checkBox1; checkBox1 = (CheckBox)findViewById(R.id.checkBox1);

2.设置监听器

checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if(isChecked){ String text = checkBox1.getText().toString(); //获得CheckedBox的文本内容 Log.i("tag",text); } } });

3.效果

RadioGroup和RadioButton控件

一、RadioGroup是RadioButton的一个集合,提供多选一机制 二、属性 android:orientation=”vertical”——垂直排布 android:orientation=”horizontal”——水平排布 三、使用 1.将数个RadioButton放到同一个RadioGroup中,设置orientation为水平排布

<RadioGroup android:id="@+id/RadioGroup1" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <RadioButton android:id="@+id/radioButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:checked="true" android:text="男" /> <RadioButton android:id="@+id/radioButton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="女" /> </RadioGroup>

2.初始化RadioButton并设置监听器

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener{ private RadioGroup rg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rg = (RadioGroup) findViewById(R.id.RadioGroup1); rg.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(RadioGroup radioGroup, @IdRes int checkedId) { switch (checkedId){ case R.id.radioButton1: Log.i("tag","man");break; case R.id.radioButton2: Log.i("tag","woman");break; } } }

3.效果

转载请注明原文地址: https://www.6miu.com/read-84016.html

最新回复(0)