在研发过程中,会经常遇到用户的性别选择,为此特地写了一篇,文章采用的是TableLayout结合TableRow实现的;
下面我们来看实现:
1.布局use_male_female.xml:
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tab" android:layout_width="match_parent" android:layout_height="match_parent"> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:text="性别:"/> <RadioGroup android:id="@+id/rg" android:orientation="horizontal" android:layout_gravity="center_horizontal"> <RadioButton android:id="@+id/male" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="男" /> <RadioButton android:id="@+id/femle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="女"/> </RadioGroup> </TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" android:id="@+id/show"/> </TableLayout>
下面我们在来看看代码实现;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.use_male_female); rg = (RadioGroup) findViewById(R.id.rg); show = (TextView) findViewById(R.id.show); rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) { tip = checkedId == R.id.male ? "男人" : "女人"; show.setVisibility(View.VISIBLE); show.setText(tip); //在这里同时可以根据小组定义数据传递到服务器; if(checkedId==R.id.male){ Toast.makeText(getApplicationContext(),"你选择了男",Toast.LENGTH_LONG).show(); }else { Toast.makeText(getApplicationContext(),"你选择了女",Toast.LENGTH_LONG).show(); } } }); } }
效果图:
以上比较简单,在开发中可以根据自己的要求进行定义,在这里就不多做解释了;
希望有帮助;
谢谢!