本文实例为大家分享了android控件radiobutton的使用代码,供大家参考,具体内容如下
内容

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" tools:context=".RadioActivity"> <RadioGroup //定义一个单选按钮组 android:id="@+id/rg_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <RadioButton //单选按钮一 使用默认样式 android:id="@+id/rb_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="男" android:textSize="24sp" android:textColor="@color/black"/> <RadioButton //单选按钮2 使用默认样式 android:id="@+id/rb_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="女" android:textSize="24sp" android:textColor="@color/black"/> </RadioGroup> <RadioGroup //组2 android:id="@+id/rg_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_below="@id/rg_1" android:layout_marginTop="50dp"> <RadioButton android:layout_width="50dp" android:layout_height="wrap_content" android:text="男" android:button="@null" //无按钮样式 android:textSize="24sp" android:background="@drawable/selector_radiobutton" //自定义背景 android:textColor="@color/black" android:checked="true" android:gravity="center"/> <RadioButton android:layout_width="50dp" android:layout_height="wrap_content" android:gravity="center" android:button="@null" //无按钮样式 android:text="女" android:background="@drawable/selector_radiobutton" //自定义背景 android:textSize="24sp" android:textColor="@color/black"/> </RadioGroup> </RelativeLayout>
//selector_radiobutton.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"> //单选被选中的样式
<shape android:shape="rectangle">
<solid android:color="#ff66ff"/>
<corners android:radius="5dp"/>
</shape>
</item>
<item android:state_checked="false"> //单选没被选中的样式
<shape android:shape="rectangle">
<stroke android:color="#cc33ff" android:width="2dp"/>
<corners android:radius="5dp"/>
</shape>
</item>
</selector>
public class RadioActivity extends AppCompatActivity {
private RadioGroup rg_1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
rg_1 = findViewById(R.id.rg_1);
rg_1.setOnCheckedChangeListener((group, checkedId) -> {//设置组中单选按钮选中事件
RadioButton radioButton = findViewById(checkedId);//获取被选中的id
Toast.makeText(RadioActivity.this,radioButton.getText(),Toast.LENGTH_SHORT)
.show();//吐司一下被选中的文本值
});
}
}
运行效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。
声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)