【发布时间】:2012-07-15 07:40:46
【问题描述】:
如果我使用 xml 文件,我有一个名为 layout_margin 的选项(例如 layout_margin ="1dp" 用于文本视图),但我想以编程方式进行设置,但我不知道该怎么做。
【问题讨论】:
标签: android
如果我使用 xml 文件,我有一个名为 layout_margin 的选项(例如 layout_margin ="1dp" 用于文本视图),但我想以编程方式进行设置,但我不知道该怎么做。
【问题讨论】:
标签: android
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)textview.getLayoutParams();
params.setMargins(20, 0, 0, 0);
textview.setLayoutParams(params);
【讨论】:
在将您的问题添加到 StackOverflow 之前,请先 Google 一下。
TextView tv = (TextView)findViewById(R.id.my_text_view);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
tv.setLayoutParams(params);
【讨论】:
你可以这样做:
TextView text = (TextView) findViewById(R.id.text);
LinearLayout.LayoutParams params= new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(left, top, right, bottom);//pass int values for left,top,right,bottom
text.setLayoutParams(params);
【讨论】:
TextView tv = (TextView) findViewById(R.id.tvId);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
tv.setLayoutParams(llp);
【讨论】:
请注意,并非所有 LayoutParams 都有方法 setMargins();
RelativeLayout、LinearLayout 等都有自己的内部类 LayoutParams,所以 setMargins 的可用性并不总是可用的。
【讨论】:
试试这个:它有效....
LinearLayout.LayoutParams Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
Params.SetMargins(0, 10, 0, 0);
FirstName.LayoutParameters = Params;
【讨论】:
您可以在LinearLayout.LayoutParams 上使用setMargins()。更多信息请参见this StackOverflow question 的回答。
【讨论】:
TextView tv = (TextView)findViewById(R.id.item_title));
RelativeLayout.LayoutParams mRelativelp = (RelativeLayout.LayoutParams) tv
.getLayoutParams();
mRelativelp.setMargins(DptoPxConvertion(15), 0, DptoPxConvertion (15), 0);
tv.setLayoutParams(mRelativelp);
private int DptoPxConvertion(int dpValue)
{
return (int)((dpValue * mContext.getResources().getDisplayMetrics().density) + 0.5);
}
textview 的getLayoutParams() 应该根据xml 中textview 的Parent 转换成对应的Params。
<RelativeLayout>
<TextView
android:id="@+id/item_title">
</RelativeLayout>
如果TextView的parent是RelativeLayout的意思,那么RelativeLayout.LayoutParams同上。如果 parent 是 LinearLayout 则意味着
LinearLayout.LayoutParams mLinearlp = (LinearLayout.LayoutParams) tv
.getLayoutParams();
要在不同的设备上渲染相同的实际尺寸,请使用我上面使用过的 DptoPxConvertion() 方法。 setMargin(left,top,right,bottom) 参数将采用 像素值而不是 dp。
【讨论】: