
文章插圖
給大家?guī)?lái)的是Andoird基本UI控件中的RadioButton和Checkbox; 先說(shuō)下本節(jié)要講解的內(nèi)容是:RadioButton和Checkbox的
1.基本用法
2.事件處理;
3.自定義點(diǎn)擊效果;
4.改變文字與選擇框的相對(duì)位置;
5.修改文字與選擇框的距離
其實(shí)這兩個(gè)控件有很多地方都是類(lèi)似的 , 除了單選和多選 , 事件處理 , 其他的都是類(lèi)似的! 另外還有一個(gè)ListView上Checkbox的錯(cuò)位的問(wèn)題 , 我們會(huì)在ListView那一章對(duì)這個(gè)問(wèn)題進(jìn)行 解決 , 好的 , 開(kāi)始本節(jié)內(nèi)容~ 本節(jié)官方文檔API:RadioButton;CheckBox;
1.基本用法與事件處理:
1)RadioButton(單選按鈕)
如題單選按鈕 , 就是只能夠選中一個(gè) , 所以我們需要把RadioButton放到RadioGroup按鈕組中 , 從而實(shí)現(xiàn) 單選功能!先熟悉下如何使用RadioButton , 一個(gè)簡(jiǎn)單的性別選擇的例子: 另外我們可以為外層RadioGroup設(shè)置orientation屬性然后設(shè)置RadioButton的排列方式 , 是豎直還是水平~
效果圖:
PS:筆者的手機(jī)是Android 5.0.1的 , 這里的RadioButton相比起舊版本的RadioButton , 稍微好看一點(diǎn)~
布局代碼如下:
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:id=”@+id/LinearLayout1″
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”
tools:context=”.MainActivity” >
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”請(qǐng)選擇性別”
android:textSize=”23dp”
/>
<RadioGroup
android:id=”@+id/radioGroup”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:orientation=”horizontal”>
<RadioButton
android:id=”@+id/btnMan”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”男”
android:checked=”true”/>
<RadioButton
android:id=”@+id/btnWoman”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”女”/>
</RadioGroup>
<Button
android:id=”@+id/btnpost”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”提交”/>
</LinearLayout>
獲得選中的值:
這里有兩種方法 ,
第一種是為RadioButton設(shè)置一個(gè)事件監(jiān)聽(tīng)器setOnCheckChangeListener
例子代碼如下:
RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup);
//第一種獲得單選按鈕值的方法
//為radioGroup設(shè)置一個(gè)監(jiān)聽(tīng)器:setOnCheckedChanged()
radgroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radbtn = (RadioButton) findViewById(checkedId);
Toast.makeText(getApplicationContext(), “按鈕組值發(fā)生改變,你選了” + radbtn.getText(), Toast.LENGTH_LONG).show();
}
});
運(yùn)行效果圖:
PS:另外有一點(diǎn)要切記 , 要為每個(gè)RadioButton添加一個(gè)id , 不然單選功能會(huì)生效!?。?br /> 第二種方法是通過(guò)單擊其他按鈕獲取選中單選按鈕的值 , 當(dāng)然我們也可以直接獲取 , 這個(gè)看需求~
以上關(guān)于本文的內(nèi)容,僅作參考!溫馨提示:如遇健康、疾病相關(guān)的問(wèn)題,請(qǐng)您及時(shí)就醫(yī)或請(qǐng)專(zhuān)業(yè)人士給予相關(guān)指導(dǎo)!
「愛(ài)刨根生活網(wǎng)」www.malaban59.cn小編還為您精選了以下內(nèi)容,希望對(duì)您有所幫助:- 2021年荒野亂斗高端局常用英雄 荒野亂斗英雄排名最新
- 掌握常用的跑步的技巧
- 講解win10低配精簡(jiǎn)版 win10 rtm版是什么意思
- 講解cad線段長(zhǎng)度計(jì)算總和 cad多條線段合成一條命令
- 抖音視頻剪輯怎么講解,抖音視頻剪輯制作教學(xué)
- java遠(yuǎn)程調(diào)用python腳本講解 java執(zhí)行python代碼
- 最常用的遠(yuǎn)程登錄協(xié)議 ftp的含義是遠(yuǎn)程登錄協(xié)議
- 常用的長(zhǎng)度面積單位換算 1厘米等于多少毫米
- 我愛(ài)測(cè)字網(wǎng)2018年生肖鼠男命配音講解
- 常用cad快捷鍵大全 cad文字標(biāo)注快捷鍵命令
