1. 程式人生 > >Android單選和多選按鈕的使用

Android單選和多選按鈕的使用

單項選擇RadioButton和多項選擇CheckBox的使用

前言:

在上一章我寫了關於安卓UI控制元件之Button,這一章就來講解下它的子類RadioButton和CheckBox。

在Android中,可以通過RadioButton和RadioGroup的組合來實現單項選擇的效果。而多項選擇則是通過CheckBox來實現的。

1、單選選擇RadioButton

我們知道,一個單項選擇是由兩部分組成的,分別是前面的選擇按鈕和後面的“答案”。

選擇按鈕可以通過RadioButton來實現,而“答案”則可以通過RadioGroup來實現。

  具體的實現步驟如下:

  首先,在佈局檔案中定義一個TextView控制元件,用來顯示問題。

  然後,再在佈局檔案中定義一個RadioGroup控制元件,用來顯示答案。

  最後,再在RadioGroup控制元件中定義四個(根據需求而定)RadioButton控制元件,並將“答案”分別賦給每個選項。

如下是單項選擇的XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <!--題目-->
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android核心是基於什麼系統?"
        android:textSize="24sp"
        />

    <RadioGroup
        android:id="@+id/radiogroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
    <RadioButton
        android:id="@+id/radiobutton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Windows"
        />
    <RadioButton
        android:id="@+id/radiobutton2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Mac os"
        />
    <RadioButton
        android:id="@+id/radiobutton3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Linux"
        />
    <RadioButton
        android:id="@+id/radiobutton4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="嵌入式系統"
        />
    </RadioGroup>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button1"
        android:layout_marginTop="50dp"
        android:text="進入下一項測試"
        />
</LinearLayout>

因為是單項選擇,所以各個選項之間存在互斥性,即僅能選中其中的某一個選項。

那麼如何來確定使用者的選擇是否正確,並給出相應的提示資訊呢?

  要確定使用者的選擇是否正確,需要知道使用者選擇的是選項中的哪一項,

這可以通過為RadioGroup設定事件監聽器setOnCheckedChangeListener來實現。

通過該事件監聽器便可以判斷出使用者點選的是哪一個RadioButton了。然後,再使用Toast來顯示相應的提示資訊即可。

用上述方案實現單項選擇demo的java原始碼如下:

package com.dsl.ui_application_07;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 功能:安卓控制元件之單項選擇按鈕
 *
 * 作者:單勝凌
 * 時間:2016.12.14
 */
public class MainActivity extends Activity {

    TextView mTV;           //用於顯示問題
    RadioGroup mRG;         //用於顯示答案
    RadioButton mRB1;       //用於顯示選項
    RadioButton mRB2;
    RadioButton mRB3;
    RadioButton mRB4;

    Button mBT;             //跳轉按鈕

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //載入佈局檔案
        //載入控制元件繫結
        mTV = (TextView)findViewById(R.id.textview);
        mRG = (RadioGroup)findViewById(R.id.radiogroup);
        mRB1= (RadioButton)findViewById(R.id.radiobutton1);
        mRB2= (RadioButton)findViewById(R.id.radiobutton2);
        mRB3= (RadioButton)findViewById(R.id.radiobutton3);
        mRB4= (RadioButton)findViewById(R.id.radiobutton4);
        mBT = (Button)findViewById(R.id.button1);
        //設定監聽器
        mRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == mRB3.getId()) {
                    MyToast("正確答案:"+mRB3.getText()+",恭喜你,回答正確");
                } else {
                    MyToast("回答錯誤!");
                }
            }
        });
        mBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳轉到下一項測試頁
                Intent intent=new Intent();
                intent.setClass(MainActivity.this, Activity_tow.class);
                startActivity(intent);
                finish();
            }
        });

    }

    private void MyToast(String str)
    {
        Toast mtoast = Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT);
        mtoast.setGravity(Gravity.TOP,0,400);
        mtoast.show();
    }
}

上敘程式碼執行效果如下:


2、多項選擇按鈕

多項選擇與單項選擇最重要的區別就是多項選擇可以讓使用者選擇一個以上的選項。

  在Android中,多項選擇是通過CheckBox來實現的,為了確定使用者是否選擇了某一項,則需要對每一個選項進行事件監聽。

  多項選擇的實現方法和單項選擇的實現方法大致相同。

  首先,在佈局檔案中定義一個TextView控制元件,用來顯示問題。

  然後,再在佈局檔案中定義四個(根據需求而定)CheckBox控制元件,分別用來顯示每一個選項。

  最後,在佈局檔案中定義一個Button控制元件,用於提交使用者所選的選項(這個可以沒有)。

  如下是多項選擇demo的xml佈局檔案:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <!--題目-->
    <TextView
        android:id="@+id/textview2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="請問你為什麼喜歡Android呢?"
        android:textSize="20sp"
        />

    <CheckBox
        android:id="@+id/checkbox1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="開源"
        />
    <CheckBox
        android:id="@+id/checkbox2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="無界限的應用程式"
        />
    <CheckBox
        android:id="@+id/checkbox3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="應用廣泛"
        />
    <CheckBox
        android:id="@+id/checkbox4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="我就是喜歡Android任性!"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:text="提交問卷"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button3"
        android:layout_marginTop="50dp"
        android:text="進入下一項測試"
        />
</LinearLayout>

當然了,我們還需要在java程式碼中實現對使用者的操作進行事件監聽,並做出相應的響應。

為此,我們需要為每一個CheckBox多項選擇選項都設定一個事件監聽器setOnCheckedChangeListener,

並通過mCheckBox.isChecked()方法來判斷該選項是否被選中(true表示被選中,false表示未選中)。

此外,我們還可以通過一個全域性變數checkedcount來統計當前有幾個選項被選中,實現方法也很簡單,

當mCheckBox.isChecked()為true時令checkedcount++;當mCheckBox.isChecked()為false時令checkedcount--就可以了。

最後,我們再為“提交”按鈕設定一個監聽器setOnClickListener,當用戶點選“提交”時,顯示一條總共選擇了幾項的提示資訊。

  多項選擇demo的java原始碼如下:

package com.dsl.ui_application_07;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;

/**
 * 功能:安卓多選按鈕Demo
 *
 * 作者:單勝凌
 * 時間:2016/12/14.
 */
public class Activity_tow extends Activity {

    CheckBox mCB1;          //用於顯示選項
    CheckBox mCB2;
    CheckBox mCB3;
    CheckBox mCB4;
    Button mBT2;            //提交檔案按鈕
    Button mBT3;            //跳轉到下一項按鈕
    int num=0;              //用於統計被選中的個數

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tow); //載入佈局檔案
        initUI();                              //初始化控制元件
        //繫結監聽器
        mCB1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(mCB1.isChecked())
                {
                    num++;
                    MyToast("你選擇了:"+mCB1.getText());
                }
                else{
                    num--;
                }
            }
        });

        mCB2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(mCB2.isChecked()){
                    num++;
                    MyToast("你選擇了:"+mCB2.getText());
                }
                else {
                    num--;
                }
            }
        });

        mCB3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(mCB3.isChecked())
                {
                    num++;
                    MyToast("你選擇了:"+mCB3.getText());
                }
                else {
                    num--;
                }
            }
        });

        mCB4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(mCB4.isChecked())
                {
                    num++;
                    MyToast("你選擇了:"+mCB4.getText());
                }
                else
                {
                    num--;
                }
            }
        });

        mBT2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyToast("謝謝您的參與,您一共選擇了"+num+"項!");
            }
        });

        mBT3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setClass(Activity_tow.this, Activity_three.class);
                startActivity(intent);
                finish();

            }
        });

    }
    private void initUI()
    {
        mCB1 = (CheckBox)findViewById(R.id.checkbox1);
        mCB2 = (CheckBox)findViewById(R.id.checkbox2);
        mCB3 = (CheckBox)findViewById(R.id.checkbox3);
        mCB4 = (CheckBox)findViewById(R.id.checkbox4);
        mBT2 = (Button)findViewById(R.id.button2);
        mBT3 = (Button)findViewById(R.id.button3);
    }

    private void MyToast(String str)
    {
        Toast mtoast = Toast.makeText(Activity_tow.this,str,Toast.LENGTH_SHORT);
        mtoast.setGravity(Gravity.TOP,0,400);
        mtoast.show();
    }

}

上述Demo執行結果如下:


3、定義自己的RadioButton單項選擇樣式

Android提供的單項選擇RadioButton式樣比較單一,如何來定製自己想要的單項選擇RadioButton式樣呢?下面給出一個簡單的實現案例。  

我們知道,Android提供的單項選擇RadioButton式樣,有三點最基本的特性:

  第一,RadioButton有兩種狀態,一種是未選中下的置灰狀態,另一種是選中下的高亮狀態,且兩種狀態互斥。

  第二,RadioButton間存在互斥性,即僅能選中其中的某一個選項。

  第三,能夠判斷出當前使用者選擇的是哪一個RadioButton選項。

  所以,我們自己定製的單項選擇RadioButton式樣至少也應該具備以上的三點特性。

3.1特性一的實現

  特性一的實現並不複雜,我們可以使用兩張不同的圖片來分別表示RadioButton的兩種狀態(選中和未選中),

而選中和未選中的狀態則可以通過android:state_checked屬性來設定。

具體可以通過在工程的res/drawable目錄下新建一個radiostyle.xml檔案來實現,

radiostyle.xml檔案的原始碼如下,其中presence_offline是選中狀態下要顯示的圖片,presence_online是未選中狀態下要顯示的圖片。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!--未選中時-->
    <item
        android:state_checked="false"
        android:drawable="@android:drawable/presence_offline"
        ></item>
    <!--選中時-->
    <item
        android:state_checked="true"
        android:drawable="@android:drawable/presence_online"
        ></item>
</selector>
3.2特性二的實現

  要實現RadioButton選項間的互斥性,可以通過mRadioButton.setChecked()方法來實現,當某一選項為true時,將其餘選項置為false即可。

3.3特性三的實現

  要判斷使用者選中的是哪一個選項,可以通過為每一個RadioButton按鈕設定一個setOnClickListener監聽器來實現。

3.4例項效果

  在本例項中,定製了一個自己的單項選擇RadioButton式樣,並且實現RadioButton式樣的上述三點最基本的特性,

達到了和1.單項選擇RadioButton中的所舉例子同樣的執行效果。執行效果如下所示。



關於Android單項選擇和多項選擇按鈕的講解到此結束!!!

原始碼地址如下:

本資源來自單勝凌!!!

Android靠自學!!!

祝各位IT人士早日取得成功!!!