繁体   English   中英

以编程方式对文本视图的布局边距

[英]layout margin for text view programmatically

如果我使用xml文件,我有一个名为layout_margin的选项(例如layout_margin =“1dp”用于文本视图),但我想以编程方式设置,我不知道该怎么做。

   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() 有关更多信息,请参阅此StackOverflow问题的答案。

        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中textviewParent转换为相应的Params。

<RelativeLayout>
   <TextView
    android:id="@+id/item_title">
</RelativeLayout>

如果TextView的父级是RelativeLayout意味着,那么RelativeLayout.LayoutParams如上所述。 如果父是LinearLayout则意味着

LinearLayout.LayoutParams mLinearlp = (LinearLayout.LayoutParams) tv
                    .getLayoutParams();

要在不同设备上呈现相同的实际大小,请使用我上面使用的DptoPxConvertion()方法。 setMargin(left,top,right,bottom)params将获取像素中的值而不是dp中的值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM