问题
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