2014-02-11 20 views
6

我的Android應用程序中有幾個按鈕。他們每個人都看起來有點像這樣:在帶有背景且沒有文字的按鈕中繪製一個可繪製的對象

<Button 
    android:id="@+id/button_1" 
    android:drawableTop="@drawable/an_icon" 
    android:background="@drawable/a_background" 
    android:layout_width="size_dp" 
    android:layout_height="size_dp"> 
</Button> 

當然,我是新來的Android開發人員,但我無法弄清楚如何居中繪製在我的按鈕。我試過按鈕和容器的不同drawableLocations,margin和padding,以及drawablePadding,但我似乎無法完成它。有沒有辦法將drawable居中而不放棄另一個View的Button?

+0

您正在使用的圖像作爲背景繪製,如果是,嘗試使用imageview的並且把它作爲一個src它會自動適合按鈕。我發現了一個鏈接,有時候你的代碼將它集中在一個真正的設備上,並且它在一個真實的設備上是可見的。試試這個吧。 http://stackoverflow.com/questions/21711468/center-a-drawable-in-a-button-with-background-and-no-text –

+0

是的,背景圖像是一個有點大的「空按鈕」,它在應用程序的許多其他地方使用。出於這個原因,我已經爲Button設置了dp的寬度和高度值(no wrap_content)。我也沒有使用圖形可視化工具 - 只是一個測試設備,以確保我所做的所有更改都反映了它的實際外觀。另外,你是否想要鏈接到這個問題? lol – HarryHippo

回答

3

有沒有辦法通過如下使用的ImageView居中繪製不放棄按鈕

所以你可以有兩個(背景&繪製):(所以不需要使用Button)

 <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/an_icon" 
     android:background="@drawable/a_background" /> 

對於Onclick o ˚FImageView的:

findViewById(R.id.imageView1).setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

      } 
     }); 
+0

問題在於它放棄了可點擊的功能,而我並不急於重新實現。但是,如果我找不到其他解決方案,這可能是一條路。 – HarryHippo

+1

ImageView提供與Button相同的可點擊功能。 –

+0

查看我更新的答案。 –

2

試試這個:

<Button 
     android:id="@+id/button_1" 
     android:drawableTop="@drawable/an_icon" 
     android:background="@drawable/a_background" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginBottom="151dp"> 
    </Button> 
+0

當我需要重新定位按鈕的內容時,對齊和邊距屬性只會將按鈕相對於其容器移動。 – HarryHippo

12

最簡單的解決方案是使用ImageButton部件:

<ImageButton 
    (...) 
    android:background="@drawable/a_background" 
    android:src="@drawable/an_icon" 
    />