android 实现男女按钮选择

在研发过程中,会经常遇到用户的性别选择,为此特地写了一篇,文章采用的是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();
}
            }
        });
       
    }
}


效果图:




以上比较简单,在开发中可以根据自己的要求进行定义,在这里就不多做解释了;

希望有帮助;

谢谢!

  • 8
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值