原理:由于android layout的的原理可见下方链接
解决方法:找出view 或viewGroup 所在的父布局,获取父布局的layoutParams
一 ViewGroup设置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>
我们需要为recycleView 设置marginBottom,xml里设置的是55dp,在底部linearLayout 设置为GONE的时候需要把marginbottom设置为0,由于recycleView的父布局是RelativeLayout,具体代码如下:
ll_buttons.setVisibility(View.GONE);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) recycleView.getLayoutParams();
lp.setMargins(0,0,0,0);
recycleView.setLayoutParams(lp);
二 View设置margin,例如imageView
RelativeLayout.LayoutParams lp1 =new RelativeLayout.LayoutParams( imageView.getLayoutParams());
lp1.setMargins(0,0,0,0);
imageView.setLayoutParams(lp1);