简体   繁体   English

通过代码更改按钮的宽度和高度

[英]Change button width and height through code

I am trying to change the width and height of Buttons I dynamically create but my code below is not working. 我正在尝试更改我动态创建的Buttonswidthheight ,但是下面的代码不起作用。 The Buttons stays the same default size. Buttons保持相同的默认大小。 Anyone know why this is not working? 有人知道为什么这行不通吗?

I believe it might have to do with this line: 我认为这可能与以下行有关:

 myButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

The problem may be that I am not supposed to create new LinearLayout params each time but rather add it to an existing LayoutParam ? 问题可能是我不应该每次都创建新的LinearLayout参数,而是将其添加到现有的LayoutParam

What do you guys think? 你们有什么感想?

public void onClick(View view)
    {

        LinearLayout linearLayout2 = new LinearLayout(view.getContext());

        linearLayout2.setOrientation(LinearLayout.HORIZONTAL);

        LinearLayout.LayoutParams rlp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);      

        int size = enter_txt.getText().toString().length();

        for (int i=0; i<size; i++){
            Button myButton = new Button(view.getContext());
            myButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            myButton.setWidth(100);
            myButton.setHeight(100);
            myButton.setBackgroundResource(R.drawable.button);
            linearLayout2.addView(myButton, rlp);
        }
     }

Change this code : 更改此代码:

myButton.setWidth(100);
myButton.setHeight(100);

To this : 对此:

myButton.getLayoutParams().width = 100;
myButton.getLayoutParams().height = 100;

And yes, in your case you can replace : 是的,在您的情况下,您可以替换:

myButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

To : 至 :

myButton.setLayoutParams(rlp);

您可以使用LinearLayout.LayoutParams其他构造函数,该构造函数接收宽度和高度:

myButton.setLayoutParams(new LinearLayout.LayoutParams(100, 100));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM