按鈕button與xml中selector選擇器的使用


Button繼承自TextView,所以TextView的一些屬性同樣也適用於Button控件。

  Button的直接子類為CompoundButton。Button的間接子類有CheckButton、RadioButton、Switch和ToggleButton。

Button常用屬性設置

1.1設置Button的背景顏色

  要設置Button按鈕的背景顏色,可以通過在xml文件中設置android:background屬性實現,同樣也可以通過在代碼中使用setBackgroundColor()方法來實現。

1.2設置Button的文字顏色

  要設置Button按鈕的文字顏色,可以通過在xml文件中設置android:textColor屬性實現,同樣也可以通過在代碼中使用setTextColor()方法來實現。

1.3設置Button的文字格式

  要設置Button按鈕的文字格式,可以通過在xml文件中設置android:textStyle屬性實現。其中,參數italic表示斜體,參數bold表示粗體。

1.4設置Button的背景圖片

  要設置Button按鈕的背景圖片,可以通過在xml文件中設置android:background屬性實現,同樣也可以通過在代碼中使用setBackgroundResource()方法來實現。

 

2.Button事件監聽器

  Button的常用事件監聽器有以下一些:

  mButton.setOnClickListener();//點擊事件監聽器

  mButton.setOnTouchListener();//觸摸事件監聽器

  mButton.setOnFocusChangeListener();//焦點狀態改變事件監聽器

  mButton.setOnKeyListener();//按鍵事件監聽器

  mButton.setOnLongClickListener();//常壓事件監聽器

   這些事件監聽器可以用來響應對Button按鈕的不同操作,使用方法比較簡單,此處就不多介紹了。

3.Button按鈕圖文混排

3.1通過設置android:drawableTop等屬性來實現

  在xml文件中,想要實現圖片環繞文字的效果,可以通過設置以下四個屬性來實現。

  android:drawableTop設置文字上方顯示的圖片

  android:drawableBottom設置文字下方顯示的圖片

  android:drawableLeft顯示文字左邊顯示的圖片

  android:drawableRight顯示文字右邊顯示的圖片

 <Button
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:drawableTop="@drawable/up"
     android:drawableBottom="@drawable/down"
     android:drawableLeft="@drawable/left"
     android:drawableRight="@drawable/right"
         android:text="OK"    >            
 </Button>

 

按下和非按下的時候按鈕顯示不同的背景

在drawable中新建一個selector標簽的xml文件如下:

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

selector標簽下的item標簽 可以設置如下屬性:
android:state_xxx 各種狀態(值為true/false) 如果值為false的話,android:state_xxx可以省略
state_pressed 按鈕按下的狀態
android:drawable 該狀態下對應顯示的圖片

布局中的引用:如果是不能點擊的控件(如ImageView)需要設置clickable為true

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/but_selector"
        android:text="@string/hello_world" />


免責聲明!

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



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