简体   繁体   中英

how to set height and width of the Dynamic button created?

I wanted to create to circle button. So I got the hint from here How to get round shape in Android . As mention in the link it is necessary to have both height and weight of button to be of same size to get shape as circle, otherwise it will be oval shape. We cannot use wrap_content than it will be oval shape.

Buy the problem is now I creating button dynamically and I try to set height and width of button same but still I am getting oval shape button instead of circle.

And I try through xml file keeping button weight and height same it's work, but through dynamic it is not. Below is the code.

for (int count = 1; count <= rowb; count++) 
{
tblRow[count] = new TableRow(getApplicationContext());
tbl.addView(tblRow[count]);

    for (int j = 1; j <= rowb; j++) {   
    String nameB=""+i;
    btn[i] = new Button(getApplicationContext());
    btn[i].setId(i);
    btn[i].setText(nameB);
    btn[i].setWidth(1);
    btn[i].setHeight(1);
    tblRow[count].addView(btn[i]);
    btn[i].setOnClickListener(getOnClickDoSomething(btn[i],i));
    i++;
    }
}
notifyAllObservers();
move--;
}

I also try but it also did,t work

TableLayout.LayoutParams lp = new TableLayout.LayoutParams(5,5);
btn[i].setLayoutParams(lp);

Can anybody let me know what the problem is ?How i get tge circle shale button instead of oval ?

You can set width and height by following code:

Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tblRow.addView(btnTag);

OR you can also set dp instend of wrap_content in it. like:

Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(30, 30));
tblRow.addView(btnTag);

I have this and it worked for me.

final Button bt = new Button(ClassListActivity.this);
bt.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 450));

The first one with MATCH_PARENT is the width. the 450 is the height. Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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