[英]How to change button size programmatically in Android?
我正在創建按鈕並以編程方式將它們添加到 LinearLayout。 但是,我正在努力更改按鈕大小。 在下面的代碼中,無論我在 deleteBtn.setWidth(num) 和 deleteBtn.setHeight(num) 中輸入什么 num,都沒有任何變化。
private void populateHorizontalLayouts(CustomMessageEvent event) {
// Need to remove all views each time an user adds a number
// so that the same number is not rendered multiple times.
nameAndNumbersLayout.removeAllViews();
//displayedNamesAndNumbers.add(event.getCustomMessage());
for(int i =0; i < displayedNamesAndNumbers.size(); i++){
String displayedNumberAndName = displayedNamesAndNumbers.get(i);
LinearLayout horizontalLayout = new LinearLayout(view.getContext());
horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);
horizontalLayout.setId(i);
Button deleteBtn = new Button(view.getContext());
deleteBtn.setId(i);
deleteBtn.setText("Delete");
deleteBtn.setWidth(5);
deleteBtn.setHeight(5);
TextView nameAndNumView = new TextView(view.getContext());
nameAndNumView.setId(i);
nameAndNumView.setText(displayedNumberAndName);
horizontalLayout.addView(deleteBtn);
horizontalLayout.addView(nameAndNumView);
nameAndNumbersLayout.addView(horizontalLayout);
}
}
我應該寫什么才能改變按鈕大小?
您應該應用包含您的Button
的LinearLayout
LayoutParams
。
deleteBtn.setLayoutParams(new LinearLayout.LayoutParams(5, 5));
試試這個
deleteBtn.setLayoutParams (new LayoutParams(LayoutParams.MATCH_PARENT, 15));
請嘗試以下操作:
int pixels = Math.round(convertDpToPixel(50, getApplicationContext()));
deleteBtn.setLayoutParams(new LinearLayout.LayoutParams(pixels, pixels));
public static float convertDpToPixel(float dp, Context context){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
return px;
}
您可以使用 LayoutParams 設置寬度和高度,通常當我使用作為參考屏幕尺寸的尺寸進行管理時。 我經常做這樣的事情:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
float targetWidth = width / 3;
float targetHeight = targetWidth * 3;
deleteBtn.setLayoutParams(new LinearLayout.LayoutParams(targetWidth, targetHeight);
如果您只想更改高度並保持寬度不變,
// This sets the height to 5 *pixels*, with keeping the width as it is.
deleteBtn.setLayoutParams (new LayoutParams(deleteBtn.getLayoutParams().getWidth(), 5));
並且只改變寬度,
deleteBtn.setLayoutParams (new LayoutParams(5, deleteBtn.getLayoutParams().getHeight()));
搜索要在 Tablerow [tbrow] 中顯示的按鈕 [del] 的答案,只會導致為出現該按鈕的 Tablerow 設置參數。
del = new Button(getApplicationContext());
del.setText("DELETE");
del.setTextColor(Color.BLACK);
del.setGravity(Gravity.END);
del.setBackgroundColor(Color.parseColor("#FFFFC107"));
del.setLayoutParams (new TableRow.LayoutParams(80, 50));
tbrow.addView(del);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.