1. 程式人生 > >LinearLayout, RelativeLayout,程式碼(動態)設定佈局位置(線性佈局,相對佈局)

LinearLayout, RelativeLayout,程式碼(動態)設定佈局位置(線性佈局,相對佈局)

有些時候我們需要動態的設定-某些佈局的位置,(也是程式碼適配)

一:父佈局是,線性佈局:

xml檔案如下

<LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/id_about_data_4"
                android:layout_width
="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="6dp" android:lineSpacingMultiplier="1.1" android:text="省錢。" android:textColor="@color/color_666666" android:textSize="@dimen/text_font_14"
/>
</LinearLayout>

程式碼設定,因為父佈局是一個線性佈局,所以我們直接new 一個線性佈局的引數,然後在給當前需要改變位置的空間設定最新的引數(相當於xml中設定)

*程式碼如下

LinearLayout.LayoutParams lp_4 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp_4.leftMargin = needLeftMargn;
lp_4.topMargin = 12; id_about_data_4.setLayoutParams(lp_4);

*如此動態設定完成

二:父佈局是,相對佈局

xml佈局如下

<RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/id_tv_top_captrue_top_1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="6dp"
                android:lineSpacingMultiplier="1.1"
                android:text="省錢。"
                android:textColor="@color/color_666666"
                android:textSize="@dimen/text_font_14" />
        </RelativeLayout>

動態設定程式碼

 RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtils.dp2px(70));//工具類哦
        layoutParams.topMargin = topHeight;

//這個api設定相對佈局,位置的                params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

        id_tv_top_captrue_top_1.setLayoutParams(layoutParams);

*如此動態設定完成