Android programmatically layout a button?

I am trying to programmatically determine the layout of my program and add a button to it in a specific position. I do not use the XML layout as a representation of the content.

RelativeLayout mainLayout; mainLayout = new RelativeLayout(this); mainLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,android.view.ViewGroup.LayoutParams.FILL_PARENT)); 

Then I added a button that I want to apply properties

 layout align center parent align left height 60px width 60px 

here is the button so far

 Button BtnNext = new Button(this); BtnNext.setWidth(60); BtnNext.setHeight(60); BtnNext.setFocusable(true); BtnNext.setId(idBtnNext); BtnNext.setText("Next"); mainLayout.addView(BtnNext, 1); 

Height and width do NOT work correctly.

+4
source share
2 answers

Hi, you can try setting the layout options

  RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); rel_btn.height = 60; rel_btn.width = 60; BtnNext.setLayoutParams(rel_btn); 

You can also add rules and set fields for the button by specifying relative layout options, such as

  rel_btn.addRule(RelativeLayout.CENTER_VERTICAL); rel_btn.leftMargin = 220; 
+3
source

The height and width will not be what you want because you are not using Density-independent pixel (dip)
The value indicated here is in pixels.
You can convert a pixel to dip using final float scale = getResources().getDisplayMetrics().density;
int dip = (int) (60 * scale + 0.5f);
final float scale = getResources().getDisplayMetrics().density;
int dip = (int) (60 * scale + 0.5f);

You will get a more accurate result.

+2
source

All Articles