使用 LinearLayout.LayoutParams 将 WRAP_CONTENT 更改为设定数字

Changing WRAP_CONTENT to a set number using LinearLayout.LayoutParams

我已经设置了一些 LinearLayout.LayoutParams 来设置一些仅使用 java 的按钮。但我想将它从 WRAP_CONTENT 更改为我选择的高度和宽度。

//LinearLayout.LayoutParams top;
//this is declared at the top as it is used by different bits of the code.
top = new LinearLayout.LayoutParams
            (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    top.topMargin = 100;
    top.leftMargin = 120;
top = new LinearLayout.LayoutParams
            (90, 80); 

// 随你喜欢

这是来自文档:

public LayoutParams(int width, int height) {
        super(width, height);
        weight = 0;
    }

根据 ViewGroup.MarginLayoutParams.html#setMargins 你必须使用这个:

LinearLayout layout = (LinearLayout)findViewById(R.id.yourLinear_Layout);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);            
params.setMargins(120, 100, 0, 0); //Here your custom margin (int left, int top, int right, int bottom)
layout.setLayoutParams(params);

你试过了吗?

top.getLayoutParams().height = 256;
top.getLayoutParams().width= 256;
top.requestLayout();

这样试试..

LinearLayout layout = (LinearLayout)findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);