Android控件與佈局——基礎控件RadioButton

        最近在用原生的控件和佈局繪製一些界面並使用,雖然這些都是Android基本知識,但是有的時候真的感覺力不從心,感覺有必要對Android常用的控件和佈局做一個系統的瞭解。後續一個月甚至更多的時間都會圍繞這個主題展開,畢竟這裏面還是有不少高級控件的,我也會盡量結合應用深入的進行了解。

上一篇:CheckBox       下一篇:CheckedTextView

今天,我們的主題是基礎控件RadioButton。在開始之前,我們還是以官方文檔爲開端來開始我們的講解,下面是Android文檔中對RadioButton的簡介:

* <p>
* A radio button is a two-states button that can be either checked or
* unchecked. When the radio button is unchecked, the user can press or click it
* to check it. However, contrary to a {@link android.widget.CheckBox}, a radio
* button cannot be unchecked by the user once checked.
* </p>

看過上一篇文章的應該可以瞭解到,這個和我們的CheckBox是十分類似的,不同的點在於,這個控件可以由非選中狀態通過點擊事件轉爲選中狀態,但是不能通過點擊實現逆向的狀態轉換,一個默認樣式RadioButton控件的非選中和選中狀態如下:

其組成和CheckBox一樣,我們同樣可以分別對其中的字體和Button進行設置,實現達到和CheckBox一樣的效果。在上面我們在簡介中得知,這個控件能通過點擊事件實現的效果如下(不能逆向改變狀態):

接下來,我們對其基本屬性進行設置,改變一下它的樣式:

 

下面我們就結合一個小例子來實際的應用一下,這個小例子就是實現多項單選功能,運行的效果如下:

佈局文件與控制邏輯如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="aoto.com.commonwidgetandlayout.basic_widget.radioButton.RadioButtonActivity">

<TextView
    android:layout_marginTop="20dp"
    android:textSize="20sp"
    android:text="請選擇您最愛的職業:"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
    <RadioButton
        android:textSize="25sp"
        android:id="@+id/radio_button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimaryDark"
        android:layout_marginStart="16dp"
        android:layout_marginTop="20dp"
        android:text="程序員" />

    <RadioButton
        android:textSize="25sp"
        android:id="@+id/radio_button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimaryDark"
        android:layout_marginStart="16dp"
        android:layout_marginTop="11dp"
        android:text="政治家" />
    <RadioButton
        android:textSize="25sp"
        android:id="@+id/radio_button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimaryDark"
        android:layout_marginStart="16dp"
        android:layout_marginTop="11dp"
        android:text="富二代" />
</LinearLayout>
package aoto.com.commonwidgetandlayout.basic_widget.radioButton;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.RadioButton;

import aoto.com.commonwidgetandlayout.R;

/**
 * @author why
 * @date 2019-5-13 20:44:28
 */
public class RadioButtonActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

    private static final String TAG = "RadioButtonActivityWhy";
    RadioButton radioButton1;
    RadioButton radioButton2;
    RadioButton radioButton3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio_button);
        radioButton1=findViewById(R.id.radio_button1);
        radioButton2=findViewById(R.id.radio_button2);
        radioButton3=findViewById(R.id.radio_button3);

        radioButton1.setOnCheckedChangeListener(this);
        radioButton2.setOnCheckedChangeListener(this);
        radioButton3.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked){
            disableOthers(buttonView.getId());
            Log.e(TAG, "您最喜歡的職業是: "+buttonView.getText().toString() );
            buttonView.setTextColor(getResources().getColor(R.color.colorPrimary));
        }
        else {
            buttonView.setTextColor(Color.BLACK);
        }
    }

    private void disableOthers(int viewId) {
        if(R.id.radio_button1!=viewId&&radioButton1.isChecked()){
            radioButton1.setChecked(false);
        }
        if(R.id.radio_button2!=viewId&&radioButton2.isChecked()){
            radioButton2.setChecked(false);
        }
        if(R.id.radio_button3!=viewId&&radioButton3.isChecked()){
            radioButton3.setChecked(false);
        }
    }
}

可見,我們爲了實現一個單選功能做了很多邏輯控制,而這樣的場景又非常多,沒有關係,我們接着官方文檔關於對其的介紹繼續向下看:

* <p>
* Radio buttons are normally used together in a
* {@link android.widget.RadioGroup}. When several radio buttons live inside
* a radio group, checking one radio button unchecks all the others.</p>

說這個RadioButton經常會結合RadioGroup一起使用,實現的功能正是我們上面所要實現的多項單選功能的操作。那下面就來看看如何使用RadioGroup實現上述例子的功能:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="aoto.com.commonwidgetandlayout.basic_widget.radioButton.RadioButton2Activity">

    <TextView
        android:layout_marginLeft="40dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="請選擇您最愛的職業:"
        android:textSize="20sp" />

    <RadioGroup
        android:id="@+id/job_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">

        <RadioButton
            android:id="@+id/radio_button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="20dp"
            android:text="程序員"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />

        <RadioButton
            android:id="@+id/radio_button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="11dp"
            android:text="政治家"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />

        <RadioButton
            android:id="@+id/radio_button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="11dp"
            android:text="富二代"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />
    </RadioGroup>
    <Button
        android:id="@+id/clear_all"
        android:text="都不喜歡"
        android:onClick="clearAll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

邏輯部分:

package aoto.com.commonwidgetandlayout.basic_widget.radioButton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import aoto.com.commonwidgetandlayout.R;

/**
 * @author why
 * @date 2019-5-13 21:43:42
 */
public class RadioButton2Activity extends AppCompatActivity {

    private static final String TAG = "RadioButton2ActivityWhy";
    RadioGroup radioGroup;
    RadioButton radioButton1;
    RadioButton radioButton2;
    RadioButton radioButton3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio_button2);
        radioGroup=findViewById(R.id.job_list);
        radioButton1=findViewById(R.id.radio_button1);
        radioButton2=findViewById(R.id.radio_button2);
        radioButton3=findViewById(R.id.radio_button3);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                getYourFavorite(checkedId);
            }
        });
    }

    /**
     * 根據ID,執行相應的邏輯
     * @param buttonId
     */
    private void getYourFavorite(int buttonId){
        switch (buttonId){
            case R.id.radio_button1:
                if(radioButton1.isChecked()) {
                    Log.e(TAG, "你最愛的職業是: " + radioButton1.getText().toString());
                }
                break;
            case R.id.radio_button2:
                if(radioButton2.isChecked()) {
                    Log.e(TAG, "你最愛的職業是: " + radioButton2.getText().toString());
                }
                break;
            case R.id.radio_button3:
                if(radioButton3.isChecked()) {
                    Log.e(TAG, "你最愛的職業是: " + radioButton3.getText().toString());
                }
                break;
        }
    }

    /**
     * 清除選型
     * @param view
     */
    public void clearAll(View view){
      radioGroup.clearCheck();
    }
}

在佈局部分,我們只需要把之前放置在佈局中的RadioButton放置在RadioGroup中即可:

<RadioGroup
        android:id="@+id/job_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">

        <RadioButton
            android:id="@+id/radio_button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="20dp"
            android:text="程序員"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />

        <RadioButton
            android:id="@+id/radio_button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="11dp"
            android:text="政治家"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />

        <RadioButton
            android:id="@+id/radio_button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="11dp"
            android:text="富二代"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />
    </RadioGroup>

邏輯部分我們首先爲RadioGroup設置狀態變化監聽

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                getYourFavorite(checkedId);
            }
        });

根據選擇的RadioButton的ID執行具體的邏輯代碼:

 /**
     * 根據ID,執行相應的邏輯
     * @param buttonId
     */
    private void getYourFavorite(int buttonId){
        switch (buttonId){
            case R.id.radio_button1:
                if(radioButton1.isChecked()) {
                    Log.e(TAG, "你最愛的職業是: " + radioButton1.getText().toString());
                }
                break;
            case R.id.radio_button2:
                if(radioButton2.isChecked()) {
                    Log.e(TAG, "你最愛的職業是: " + radioButton2.getText().toString());
                }
                break;
            case R.id.radio_button3:
                if(radioButton3.isChecked()) {
                    Log.e(TAG, "你最愛的職業是: " + radioButton3.getText().toString());
                }
                break;
        }
    }

注意到在這裏我們只實現了數據的獲取(RadioButton的文本內容),RadioGroup中的RadioButton之間的狀態管理(單選)是RadioGroup內部自己管理的,這爲我們節省很多的開發邏輯,也是我們用它的主要目的。此外,這裏,我們還可以通過調用clearCheck()實現清除選擇狀態。

radioGroup.clearCheck()

運行結果如下所示:

同樣,如果你覺得RadioButton中的Button樣式不好看,你可以自定義一種,這裏,我們還是選用上一篇中的樣式代碼,執行效果如下:

修改按鈕樣式是通過android:button屬性:

 <RadioButton
            android:id="@+id/radio_button1"
            android:button="@drawable/check_box_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="20dp"
            android:text="程序員"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />

其中的check_box_back.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/chosen"></item>
    <item android:state_checked="false" android:drawable="@drawable/non_chosen_big"></item>
</selector>

該控件的開源項目在網上找了一下,感覺沒有什麼比較好的,主要是因爲它的封裝程度已經很高了,如果只是想改動一下顯示樣式和邏輯,我們自己完全可以實現。好了,關於RadioButton到這裏的簡單介紹就介紹了。

上一篇:CheckBox       下一篇:CheckedTextView  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章