Adding margins to button object programatically

余生长醉 提交于 2019-12-12 02:57:48

问题


Need to set left margin to a button object programatically. This is the code segment:

RelativeLayout rl = (RelativeLayout) findViewById(R.id.for_button);
MarginLayoutParams ml = new MarginLayoutParams(-2,-2);
ml.setMargins(5, 0, 0, 0);

Button btn = new Button(this);
btn.setText("7");
btn.setTextColor(Color.WHITE);
btn.setBackgroundResource(R.drawable.date_button);

rl.addView(btn,ml)

I also tried

btn.setLayoutParams(ml);
rl.addView(btn);

Whats the big problem. Or is there any alternative way?


回答1:


You use a RelativeLayout as the parent for the button, but you don't specify any rules for the it where to place the button (e.g. ALIGN_PARENT_LEFT and ALIGN_PARENT_TOP).

You have to set rules for position when using a RelativeLayout though, so this messes with the layout calculation. This means that you have to use RelativeLayout.LayoutParams instead of the MarginLayoutParams because the former allows these rules and has proper default values set.

Alter this line:

MarginLayoutParams ml = new MarginLayoutParams(-2,-2);

to

RelativeLayout.LayoutParams ml = new RelativeLayout.LayoutParams(-2,-2);

Chances are that you also want to add rules because the default positioning values don't suit you (views get positioned in the top left corner of the parent layout by default). You can use RelativeLayout.LayoutParams.addRule() for that.




回答2:


Alright, I'm gonna give this a shot IronBlossom; this is how I do it and I hope it works:

LinearLayout myLinearLayout = (LinearLayout)findViewById(R.id.my_linear_layout);
Button myButton = new Button(this);
// more myButton attribute setting here like text etc //

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(5,0,0,0);
myLinearLayout.addView(myButton, params);

best,

-serkan



来源:https://stackoverflow.com/questions/8312215/adding-margins-to-button-object-programatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!