Android 按鈕類控件大集錦:Button ToggleButton CheckBox RadioButton


 

Button

  Button的基本使用之前已經討論過:

  http://www.cnblogs.com/mengdd/archive/2012/12/20/2826235.html

  其中介紹了兩種處理點擊的方法:一種是通過在布局文件中設置onClick屬性;另一種是通過在程序中設置Listener。

  這兩種方法對於本文中其他控件也適用,只不過第二種方法可能具體函數名稱會有所變化。

  對於Button的應用補充一些內容:

  Button可以有文字的、圖形的、或者文字和圖形都有的。

  主要是文字的,在布局文件中聲明 Button 即可;圖形的,就聲明為ImageButton,並且添加屬性src

  比如:

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/button_icon"
    ... />

 

  如果是文字和圖形都有,則使用 Button 類,但是加上android:drawableLeft 屬性設置圖像:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_text"
    android:drawableLeft="@drawable/button_icon"
    ... />
 
        

Styling Your Button

  可以設置按鈕的風格和主題,這部分內容先不詳述,如有興趣可以轉向文末尾的參考鏈接。

 

無邊按鈕

  加上屬性style="?android:attr/borderlessButtonStyle"

  如:

<Button
    android:id="@+id/button_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage"
    style="?android:attr/borderlessButtonStyle" />
 
        

自定義背景

  可以定義按鈕各種狀態對應的圖片,首先需要把這些圖片資源加入進來,然后在res/drawable/目錄下創建一個XML文件,將狀態和對應的圖片綁定;最后在Button的android:background 屬性中加入該XML文件的名字。

  比如:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_default" />
</selector>

 

  注意到這個文件中item的順序是很重要的,當這個drawable資源被引用時,<item>元素會按順序被查詢如果匹配立即返回,不再向后查詢

  所以把默認的情況放在最后,當前面的狀態都不匹配時,顯示默認圖像。

  

<Button
    android:id="@+id/button_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage"
    android:background="@drawable/button_custom"  />

   

  drawable除了可以是圖片以外,也可以是自己定義的shape,比如這個state_list其中的drawable就是自己定義的shape(當然從這個文件中是看不出來的,它們和圖像的引用方式沒有差別):

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

    <item android:drawable="@drawable/shape_one" android:state_pressed="true"/>
    <!-- pressed -->
    <item android:drawable="@drawable/shape_two" android:state_focused="true"/>
    <!-- focused -->

    <item android:drawable="@drawable/shape_three"/>
    <!-- default -->

</selector>

  

 

  其中自定義的shape:shape_one.xml:

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

    <gradient
        android:angle="45"
        android:endColor="#80FFBBFF"
        android:startColor="#FFFFBB00" />

    <padding
        android:bottom="7dp"
        android:left="7dp"
        android:right="7dp"
        android:top="7dp" />

    <corners android:radius="8dp" />

</shape>

 

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

    <solid android:color="#FFFF00FF" />

    <padding
        android:bottom="7dp"
        android:left="7dp"
        android:right="7dp"
        android:top="7dp" />

    <corners android:radius="8dp" />

</shape>
shape_two.xml

 

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

    <solid android:color="#FFFFFFFF" />

    <padding
        android:bottom="7dp"
        android:left="7dp"
        android:right="7dp"
        android:top="7dp" />

    <corners android:radius="8dp" />

    <stroke
        android:width="5dip"
        android:color="#555" />

</shape>
shape_three.xml


  具體可以參見:API Guides: Drawable Resources

  http://developer.android.com/guide/topics/resources/drawable-resource.html


自定義Button字體顏色:

  根據上面的思路,字體顏色也可以采用自定義變化的方式:

  比如設置Button的屬性如下:

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/myTextView"
        android:background="@drawable/button_state_list"
        android:text="Test Button"
        android:textColor="@drawable/btn_text_color_state_list" />

 

  其中btn_text_color_state_list.xml:

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

    <item android:state_pressed="true" android:color="#ffff0000"/>
    <!-- pressed -->
    <item android:state_focused="true" android:color="#ff0000ff"/>
    <!-- focused -->
    <item android:color="#ff000000"/>
    <!-- default -->

</selector>


 

Toggle Buttons

  這種按鈕ToggleButton只涉及兩種狀態的轉換,Android 4.0 (API level 14)開始,引入了 Switch,可以進行滑動控制,如下圖:

  

 

  可以更改android:textOnandroid:textOff屬性,設置按鈕狀態為true和false時的文字。

 

 

復選框Checkbox

    復選框類 CheckBox 是CompoundButton類的子類,而CompoundButton類是Button類的子類,是帶有選擇和未選擇狀態的Button。

  關於實現,直接看代碼吧。

 

單選按鈕

  單選按鈕用於從一個集合中選中一項。

  單選組將用戶的可選項全部羅列出來,讓用戶選擇一個,如果不需要全部羅列出來,可以考慮換用spinner,關於spinner的使用先不贅述。

  每一個單選按鈕項是一個 RadioButton ,因為單選項目是互斥的,所以需要把它們結成組,組成 RadioGroup,系統會使得一組中每次只要一個被選中。

  RadioButton和CheckBox一樣,都是CompoundButton的子類。

  而RadioGroup卻繼承自LinearLayout,默認是垂直布局。

 

  除了給每個RadioButton的onClick屬性賦值以外(同一個函數名),還可以通過對RadioGroup設置事件監聽。

  調用RadioGroup對象的setOnCheckedChangeListener方法。

 

  RadioButton不像CheckBox那樣,RadioButton不可以通過二次點擊來取消選擇。

  但是可以通過在RadioGroup外部的按鈕之類的,對整個RadioGroup進行清除,清除后,checkedId變為-1,表示沒有單選按鈕被選擇。

  

  

程序實例

  還是看直接的例子比較簡單有效:

  程序運行如下圖:

  

 

 

  例子中:

  第一個按鈕是無邊框按鈕;

  第二個按鈕本來是一個小按鈕,后來用於實踐了自定義背景的效果,按鈕被點擊和獲得焦點時的圖片與默認圖片不同;

  第三個按鈕是一個ImageButton,通過這個按鈕試了試長按和點擊的事件;

  之后是兩個Toggle Button,第一個是默認文字,添加了事件相應,第二個更改了兩種狀態的文字;

  之后是Check Box和Radio Group。

  這里利用了最初的第一個按鈕,作為一個重置按鈕,將多選和單選的狀態都設置為沒有選擇,並且兩個Toggle Button都設置為false。

 

代碼

布局文件:

activity_hello_button.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="36dp"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        style="?android:attr/borderlessButtonStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="@string/btn" />

    <Button
        android:id="@+id/button2"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_custom"
        android:text="@string/small_btn" />

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:layout_marginLeft="10dip"
        android:contentDescription="@string/image_des"
        android:src="@drawable/pic3" />

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/toggle" />

    <ToggleButton
        android:id="@+id/toggleButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/toggle"
        android:textOff="@string/toggle_off"
        android:textOn="@string/toggle_on" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/check" />

    <TextView
        android:id="@+id/radioText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="@string/radio0" />

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio1" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio2" />
    </RadioGroup>

</LinearLayout>

Activity代碼:

HelloButton.java
package com.example.hellobutton;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.support.v4.app.NavUtils;

public class HelloButton extends Activity
{

    Button btn1;
    Button btn2;
    ImageButton imageBtn;

    ToggleButton tBtn1;
    ToggleButton tBtn2;

    CheckBox checkBox;

    TextView textView;
    RadioGroup radioGroup;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello_button);

        findViews();

        setListeners();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.activity_hello_button, menu);
        return true;
    }

    private void findViews()
    {
        btn1 = (Button) findViewById(R.id.button1);
        btn2 = (Button) findViewById(R.id.button2);
        imageBtn = (ImageButton) findViewById(R.id.imageButton1);

        tBtn1 = (ToggleButton) findViewById(R.id.toggleButton1);
        tBtn2 = (ToggleButton) findViewById(R.id.toggleButton2);

        checkBox = (CheckBox) findViewById(R.id.checkBox1);

        textView = (TextView) findViewById(R.id.radioText);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);

    }

    private void setListeners()
    {

        // 第一個按鈕事件
        btn1.setOnClickListener(new View.OnClickListener()
        {

            public void onClick(View v)
            {
                // 將Toggle Button置為false
                tBtn1.setChecked(false);
                tBtn2.setChecked(false);

                // 將復選框置回起始狀態
                checkBox.setChecked(false);
                checkBox.setText(R.string.check);

                // 將單選框置為什么也沒選
                radioGroup.clearCheck();

            }
        });

        // 第二個按鈕事件
        btn2.setOnClickListener(new View.OnClickListener()
        {

            public void onClick(View v)
            {

            }
        });
        // ImageButton有長按和點擊兩種操作,可以發現點擊是在用戶松開的瞬間處理的,因為長按結束后松開,會出現點擊信息
        imageBtn.setOnClickListener(new View.OnClickListener()
        {
            // 點擊

            public void onClick(View v)
            {
                Toast.makeText(HelloButton.this, "Image Button is Clicked",
                        Toast.LENGTH_SHORT).show();

            }
        });

        //ImageButton長按
        imageBtn.setOnLongClickListener(new View.OnLongClickListener()
        {
            // 長按

            public boolean onLongClick(View v)
            {
                Toast.makeText(HelloButton.this,
                        "Image Button is Long Pressed!", Toast.LENGTH_LONG)
                        .show();
                return false;
            }
        });

        // Toggle Button
        tBtn1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {

            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked)
            {
                if (isChecked)
                {
                    Toast.makeText(HelloButton.this,
                            "The Toggle Button is Checked!", Toast.LENGTH_SHORT)
                            .show();
                }
                else
                {
                    Toast.makeText(HelloButton.this,
                            "The Toggle Button is NOT Checked!",
                            Toast.LENGTH_SHORT).show();

                }

            }
        });

        // 復選框被點擊事件
        checkBox.setOnClickListener(new View.OnClickListener()
        {

            public void onClick(View v)
            {

                checkBox.setText(checkBox.isChecked() ? R.string.checked
                        : R.string.not_checked);

            }
        });

        // 復選框選擇改變事件
        // 注意此事件除了用戶點擊會激發以外,程序內的重置操作,只要改變了復選框選擇內容(從無到有或從有到無),就會調用這個函數
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {

            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked)
            {
                Toast.makeText(HelloButton.this, "Check Box has changed!",
                        Toast.LENGTH_SHORT).show();

            }
        });

        // 單選框組
        radioGroup
                .setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
                {

                    public void onCheckedChanged(RadioGroup group, int checkedId)
                    {
                        if (checkedId != -1)
                        {
                            RadioButton rButton = (RadioButton) findViewById(checkedId);
                            if (rButton != null)
                            {
                                textView.setText("You have chosen: "
                                        + rButton.getText());
                            }
                        }
                        else
                        {
                            textView.setText("Choose one!");

                        }

                    }
                });

    }

}

Button自定義圖片效果需要的配置文件(放在res/drawable/目錄下):

button_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_default" />
</selector>

字符串資源文件:

strings.xml
<resources>

    <string name="app_name">HelloButton</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_hello_button">HelloButton</string>
    <string name="btn">Button</string>
    <string name="small_btn">Small Button</string>
    <string name="toggle">Toggle Button</string>
    <string name="toggle_on">Toggle On</string>
    <string name="toggle_off">Toggle Off</string>
    <string name="image_des">Just a normal .jpg image file.</string>
    <string name="check">Check Box</string>
    <string name="checked">This option is checked!</string>
    <string name="not_checked">This option is NOT checked!</string>
    <string name="radio0">Radio Button1</string>
    <string name="radio1">Radio Button2</string>
    <string name="radio2">Radio Button3</string>

</resources>

 

 

參考資料

  API Guides: Buttons

  http://developer.android.com/guide/topics/ui/controls/button.html

  API Guides: Styles and Themes

  http://developer.android.com/guide/topics/ui/themes.html

  API Guides: Toggle Buttons

  http://developer.android.com/guide/topics/ui/controls/togglebutton.html

  API Guides: Checkboxes

  http://developer.android.com/guide/topics/ui/controls/checkbox.html

  API Guides: Radio Buttons

  http://developer.android.com/guide/topics/ui/controls/radiobutton.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM