Principle: Due to the principle of android layout, you can see the link below
ANDROID custom view - onLayout source code
Solution: Find out the parent layout where the view or viewGroup is located, and get the layoutParams of the parent layout
A ViewGroup sets the margin
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activity.DeviceSimpleDetailActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recycleView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/titlebar" android:layout_marginBottom="55dp" /> <LinearLayout android:id="@+id/ll_buttons" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginBottom="@dimen/margin10" android:background="@color/white" android:layout_alignParentBottom="true" android:orientation="horizontal" > <Button android:id="@+id/bt_left" android:layout_width="0dp" android:layout_height="match_parent" android:layout_marginRight="1dp" android:layout_weight="1" android:background="@color/blue" android:text="@string/pass" android:textColor="@color/white" android:textSize="@dimen/text_size_mid" /> <Button android:id="@+id/bt_right" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@color/blue" android:text="@string/reject" android:textColor="@color/white" android:textSize="@dimen/text_size_mid" /> </LinearLayout> </RelativeLayout>
We need to set marginBottom for recycleView, which is set to 55dp in xml. When the bottom linearLayout is set to GONE, marginbottom needs to be set to 0. Since the parent layout of recycleView is RelativeLayout, the specific code is as follows:
ll_buttons.setVisibility(View.GONE); RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) recycleView.getLayoutParams(); lp.setMargins(0,0,0,0); recycleView.setLayoutParams (lp);
Two View settings margin, such as imageView
RelativeLayout.LayoutParams lp1 =new RelativeLayout.LayoutParams( imageView.getLayoutParams()); lp1.setMargins(0,0,0,0); imageView.setLayoutParams (lp1);