2011-05-23 82 views
3

我有一個ImageButton。代碼是 -Android - 如何以編程方式更改ImageButton的寬度?

ImageButton shareButton = new ImageButton(this); 
shareButton.setBackgroundResource(android.R.drawable.ic_menu_share); 

RelativeLayout.LayoutParams shareParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
shareParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, navigationLogo.getId()); 

shareButton.setLayoutParams(shareParams); 

我需要更改它的寬度。但ImageButton和佈局參數都沒有setWidth方法。看了很多網上沒有答案。

回答

8

而不是使用RelativeLayout.WRAP_CONTENT寬度,您可以使用實際的數字,這將是按鈕的新的寬度(以像素爲單位)。因爲你很可能要指定DP寬度是與分辨率無關的,你可能需要DP轉換爲像素,使用方法如下所示:

public static int dpToPixels(Context context, float dp) { 
    final float scale = context.getResources().getDisplayMetrics().density; 
    return (int) (dp * scale + 0.5f); 
} 
0

試試這個。

ImageButton shareButton = new ImageButton(this); 
shareButton.setBackgroundResource(android.R.drawable.ic_menu_share); 

RelativeLayout.LayoutParams shareParams = new RelativeLayout.LayoutParams(
     LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
shareParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, navigationLogo.getId()); 
shareParams.width = INTEGER_NUMBER; 
shareButton.setLayoutParams(shareParams); 
相關問題