create and set margin programmatic for relative layout android

你离开我真会死。 提交于 2020-01-23 17:13:32

问题


Hi I am developing android application in which I am creating relative layout programmatic and tried to set margin for that and Added it into linear layout which have orientation linear. So here is my code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/screen_background"
    tools:context=".ChooseChannelsFragment" >

    <LinearLayout 
      android:id="@+id/main_outer_llt"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="horizontal"
      >

  </LinearLayout> 

</RelativeLayout>

and inside fragment I am adding relative layout like this

RelativeLayout relativeLayout = new RelativeLayout(getActivity());
    RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(200, 80);
    relativeParams.setMargins(20, 20, 20, 20);
    relativeLayout.setLayoutParams(relativeParams);
    relativeLayout.setBackgroundColor(getResources().getColor(R.color.green_color));
    linearLayout.addView(relativeLayout);

It create layout with given color and size but not accepting margins. Am I doing something wrong? How to do this? Need Help. Thank you.


回答1:


The LayoutParams type you use on a view should actually be from its parent.

So, if you're adding a RelativeLayout to a LinearLayout, the LayoutParams you set to your RelativeLayout should actually be a LinearLayout.LayourParams, and not a RelativeLayout.LayoutParams.




回答2:


As others suggested, layout_margin# is the space between the parent's # edge and your view.

  • # replaces "Left", "Right", "Top" or "Bottom"

Getting/setting margins worked for me with:

ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mView.getLayoutParams();
params.topMargin += 20;
mView.requestLayout(); // important

Of course, my View was indeed a ViewGroup and the parent was a ViewGroup as well. In most cases, you should cast your layout params to the parent's View class LayoutParams (in this case it's ViewGroup and RelativeLayout)




回答3:


In this case, the father is LinearLayout. So you should use:

TableLayout.LayoutParams layoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(20, 20, 20, 20);


来源:https://stackoverflow.com/questions/19342269/create-and-set-margin-programmatic-for-relative-layout-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!