2011-06-16 20 views
5

在iOS中,如果我將按鈕的背景設置爲圖像,當我按下按鈕時,按鈕的全部內容(包括文本)將被遮蔽。我可以在Android中獲得相同的效果,還是必須針對不同的狀態使用不同的圖像?另外,即使我爲不同的狀態使用不同的圖像,我如何讓文字也被遮蔽?一個骯髒的方法是將OnClickListener設置爲按鈕,並按下時以編程方式遮蔽文本,但還有其他方法嗎?按下時自動更改按鈕背景和文字外觀(如iOS)?

+0

它是一個切換按鈕,其中狀態可以是向上或向下,或常規按鈕它纔會出現不同,因爲它是被點擊? – TomHarrigan 2011-06-16 23:50:57

+0

這是一個常規按鈕。 – hzxu 2011-06-17 00:24:54

回答

7

我一直在嘗試爲此找到一個解決方案,但無法找到任何東西,所以我想出了一個漂亮的解決方案,它適用於所有圖像按鈕。就像iOS一樣。

  • 創建一個黑色,10%透明圖像並將其保存爲PNG。我稱之爲button_pressed.png。您可以使用此圖片,http://img84.imageshack.us/img84/7924/buttonpressed.png

  • 創建一個名爲相關繪製的東西,我把它叫做「button_pressed_layout.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="@drawable/button_pressed" /> 
    </selector> 
    
  • 現在擺在你的LinearLayout按鈕圖像,然後將按鈕的的LinearLayout內。在按鈕中使用button_pressed_layout.xml作爲背景。

    <LinearLayout 
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content" 
         android:background="@drawable/button_image"> 
         <Button 
          android:id="@+id/myButtonId" 
          android:text="@string/Continue" 
          android:layout_width="fill_parent" 
          android:layout_height="fill_parent" 
          android:background="@drawable/button_pressed_layout" 
          android:textColor="#FFF" 
          android:textSize="16dp" >     
         </Button> 
        </LinearLayout> 
    

That's吧!

0

爲了給按鈕本身不同的效果,我相信你需要使用自定義圖像,看到here,並不太詳細here至於文字,this post看起來它會爲影子做的伎倆

2

爲了在不創建第二個按鈕圖像的情況下獲得按下狀態,我創建了一個OnTouchListener來更改按鈕的alpha。這不是最美麗的按下狀態,但會產生有效的自動行爲。

public class PressedStateOnTouchListener implements OnTouchListener 
{ 
    PressedStateOnTouchListener(float alphaNormal) 
    { 
     mAlphaNormal = alphaNormal; 
    } 

    public boolean onTouch(View theView, MotionEvent motionEvent) 
    { 
     switch(motionEvent.getAction()) { 
      case MotionEvent.ACTION_DOWN: 
       theView.setAlpha(mAlphaNormal/2.0f); 
       break; 

      case MotionEvent.ACTION_UP: 
       theView.setAlpha(mAlphaNormal); 
       break; 
     } 

     // return false because I still want this to bubble off into an onClick 
     return false; 
    } 

    private float mAlphaNormal; 
} 

在你的活動,適用本聽者每一個按鈕:

Button theButton = (Button)findViewById(R.id.my_button_id); 
theButton.setOnTouchListener(new PressedStateOnTouchListener(theButton.getAlpha())); 
+0

這給出了按下狀態的「相反」。您應該將圖像變暗以顯示按下,而不是變亮。並在白色的背景,這減輕了它。 – dacopenhagen 2014-03-03 21:50:33