2012-11-13 90 views
8

任何人都可以向我解釋爲什麼會發生這種情況嗎?填充不適用於某些背景資源

我有一個相當簡單的類擴展TextView。當我將背景色設置爲Color.BLUE時,填充效果很好。當我將背景資源更改爲android.R.drawable.list_selector_background時,我的填充不再適用。什麼是F?

這裏是我的UI類:

public class GhostDropDownOption extends TextView { 

    TextView text_view; 


    public GhostDropDownOption(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     setup(context); 
    } 


    public GhostDropDownOption(Context context) { 
     super(context); 
     setup(context); 
    } 


    private void setup(Context context) { 
     this.setClickable(false); 
     // THE 2 LINES BELOW ARE THE ONLY THING I'M CHANGING 
     //this.setBackgroundResource(android.R.drawable.list_selector_background); 
     this.setBackgroundColor(Color.BLUE); 
    } 
} 

而且我使用它在像這樣的佈局:

<trioro.voyeur.ui.GhostDropDownOption 
    android:id="@+id/tv_dropdown_option_1" 
    android:layout_width="fill_parent" 
    android:layout_height="0dip" 
    android:layout_weight="1" 
    android:gravity="center_vertical" 
    android:text="@string/request_control_dropdown_option_1" 
    android:textColor="#000000" 
    android:padding="10dip"/> 

這是改變背景的結果: enter image description here

回答

11

致電:

this.setBackgroundResource(android.R.drawable.list_selector_background); 

將刪除任何以前設置的填充(這是爲了使它適用於9修補程序資產)。

嘗試設置填充在代碼行後上方,這樣的:

this.setPadding(PADDING_CONSTANT, PADDING_CONSTANT, PADDING_CONSTANT, PADDING_CONSTANT); 

只要記住,發送到setPadding值是以像素沾!

+1

更多信息可以在這裏找到:http://stackoverflow.com/questions/2886140/does-changing-the-background-also-change-the-padding-of-a-linearlayout – TofferJ

2

如果可能的話,你應該用XML設置你的背景。如果將它設置爲代碼,它將使用可繪製資源中的填充而不是您在XML中設置的內容,因此如果需要以編程方式執行此操作,則需要檢索當前填充,暫時存儲它,設置背景,然後按照@TofferJ的建議設置填充。

其原因是繪圖本身可以有填充,在9補丁圖像的情況下(其中底部和右側像素邊界定義了填充量)。

您的解決方案應該是隻設置你的背景資源的XML:

android:background="@android:drawable/list_selector_background"

雖然我相信可能是你必須複製到項目第一私人繪製資源。

+1

謝謝,這是一個偉大的解決方案,因爲我只使用我的UI類的幾個實例。原來我沒有把它複製到我的項目中。該行將從安裝應用程序的任何設備中獲取內置的繪圖。 – raydowe