簡體   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