当前位置: 动力学知识库 > 问答 > 编程问答 >

java - WHEN to programatically resize a button created programatically?

问题描述:

Ok hopefully this is an easy question and someone can answer.

I am creating some buttons in a tablelayout. I am creating the buttons programmatically.

For example the following code is in the "onresume" method...

TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);

TableRow.LayoutParams rowParams = new TableRow.LayoutParams(0,android.widget.TableRow.LayoutParams.MATCH_PARENT,3f);

TableLayout tableLayout = (TableLayout) findViewById(R.id.sometablelayoutivealreadydefinedinxml);

TableRow tableRow = new TableRow(this);

tableRow.setLayoutParams(tableParams);

Button btnOne = new Button(this);

btnOne.setId(100);

btnOne.setLayoutParams(rowParams);

btnTwo.setId(200);

btnTwo.setLayoutParams(rowParams);

tableRow.addView(btnOne);

tableRow.addView(btnTwo);

tableLayout.addView(tableRow);

I want to set the height of the button to be the SAME as the width. The width is determined by the size of the screen. The problem as I understand it,is that until the buttons are actually drawn to the screen they don't exist so any width returned will be zero. So I tried the following code.

Button yourBtn = (Button)findViewById(100);

int btnSize;

btnSize = yourBtn.getWidth();

yourBtn.setLayoutParams(new TableRow.LayoutParams(btnSize, btnSize));

Now the problem is that if I run this code immediately after creating the buttons the width of the button is returned as 0 as the button hasn't been drawn yet. However, if I assign the code to a test button then it resize the button as I want it to. However, I don't want the user to have to press a button after the screen has loaded to resize the buttons properly.

So, the question is when is the appropriate time to call this to resize the buttons properly when the activity is created but after the buttons have been drawn and how do I do this?

Thank you in advance

分享给朋友:
您可能感兴趣的文章:
随机阅读: