2012-06-27 58 views
0

我創建使用的RelativeLayout填充圖像按鈕:機器人

和按鈕圖像我使用以下代碼的簡單的工具欄,

ImageButton back = new ImageButton(ctx.getContext()); 
       RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
       backLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL); 


       back.setLayoutParams(backLayoutParams); 
       back.setContentDescription("Back Button"); 
       back.setId(2); 
       try { 
        back.setImageBitmap(loadDrawable("icon_left.png")); 
       } catch (IOException e) { 
        Log.e(LOG_TAG, e.getMessage(), e); 
       } 
       back.setOnClickListener(new View.OnClickListener() { 
        public void onClick(View v) { 
         // 
        } 
       }); 

將其添加到工具欄

toolbar.addView(back); 

工具欄我使用,

RelativeLayout toolbar = new RelativeLayout(ctx.getContext()); 
toolbar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,60));   

問題在於按鈕圖像在佈局參數中不包含FILLS。

我嘗試使用setMargin它的工作原理,但它不符合各種屏幕分辨率。

enter image description here

需要關於如何做到這一點的方向。

回答

0

默認情況下替換代碼

back.setImageBitmap(loadDrawable("icon_left.png")); 

ImageButton使其圖像就像後面的按鈕,背景Button在它的文字背後。

通過在代碼中調用setBackgroundDrawable(null)來禁用背景。

+0

已嘗試back.setBackgroundDrawable(null);但dint工作 –

2

嘗試將背景圖片設置爲背景 - 它應該由Android操作系統自動縮放。我建議你將該圖片轉換爲.9.png,以便它不會拉伸文本,只是按鈕的外觀。

順便說一句,真棒看按鈕那裏。

編輯: 你的代碼仔細尋找後,我想你可以簡單地用

back.setBackgroundDrawable(loadDrawable("icon_left.png")); 
+0

plz顯示了一些關於如何獲得這個的例子。 –

+0

你應該使用下面的xml代碼: android:background =「@ drawable/icon_left.png」 – pogo2065

+0

我正在尋找一個基於代碼的解決方案而不是xml。 thnx的迴應,雖然 –

1

它不填寫的佈局,因爲你寫的:

RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 

什麼是你想要的結果呢?

+0

我想顯示一個圖像按鈕,它應根據屏幕大小自動縮放。 –