Android, programmatically layout a button view?
I am trying to programmatically define my program layout and add a button t开发者_C百科o it at a certain position. I am not using the layout xml as the content view.
RelativeLayout mainLayout;
mainLayout = new RelativeLayout(this);
mainLayout.setLayoutParams(new
LayoutParams(LayoutParams.FILL_PARENT,android.view.ViewGroup.LayoutParams.FILL_PARENT));
I have then added a button that I want to apply the 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 DON'T work correctly.
Hi you can try by setting layout params
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 margins for Button by setting relative layout params like
rel_btn.addRule(RelativeLayout.CENTER_VERTICAL);
rel_btn.leftMargin = 220;
Height and width will not be as u wished because your are not using Density-independent pixel (dip)
The value you set here is in pixel
You can convert the pixel into dip by
final float scale = getResources().getDisplayMetrics().density;
int dip = (int) (60 * scale + 0.5f);
You will get more accurate result
精彩评论