添加边距按钮对象编程 [英] Adding margins to button object programatically
问题描述
需要左旁编程设置为一个按钮对象。
这是code段:
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)
我也试过
btn.setLayoutParams(ml);
rl.addView(btn);
请告诉我大问题。或是否有任何替代办法?
Whats the big problem. Or is there any alternative way?
推荐答案
您使用的RelativeLayout父的按钮,但你不要在何处放置该按钮指定任何规则的(如 ALIGN_PARENT_LEFT
和 ALIGN_PARENT_TOP
)的。
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
).
您有无的使用一个RelativeLayout的,虽然当位置设置的规则,所以这个食堂与布局计算。这意味着,你必须使用 RelativeLayout.LayoutParams
而不是 MarginLayoutParams
,因为前者允许这些规则,并有适当的默认值设置的。
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.
改变这一行:
MarginLayoutParams ml = new MarginLayoutParams(-2,-2);
到
RelativeLayout.LayoutParams ml = new RelativeLayout.LayoutParams(-2,-2);
有机会,你也想添加规则,因为默认定位值不适合你的(观点得到定位在默认情况下,父布局的左上角)的。您可以使用<一个href=\"http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#addRule%28int%29\"相对=nofollow> RelativeLayout.LayoutParams.addRule()
了点。
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.
这篇关于添加边距按钮对象编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!