由于项目中列表类页面比较多,所以就想着能不能搞一个通用的ViewController去展示页面,同时页面预留下两个LinearLayout去给需要展示的其他控件留有余地。
简单来说,就是这样的:
<RelativeLayout android:id="@+id/parent" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/top" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:orientation="vertical" /> <com.scwang.smartrefresh.layout.SmartRefreshLayout android:id="@+id/refresh" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/bottom" android:layout_below="@+id/top" android:background="@color/white" app:srlEnablePreviewInEditMode="false"> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.scwang.smartrefresh.layout.SmartRefreshLayout> <LinearLayout android:id="@+id/bottom" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="vertical" /> </RelativeLayout>但是有时候也需要refresh在填充不满中间的区域的情况下,下面的布局能顶上去并且能保持一定的距离,话不多说,直接上代码:
RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams) refresh.getLayoutParams(); param.height = ViewGroup.LayoutParams.WRAP_CONTENT; param.width = ViewGroup.LayoutParams.MATCH_PARENT; param.removeRule(RelativeLayout.ABOVE); refresh.setLayoutParams(param); RelativeLayout.LayoutParams param1 = (RelativeLayout.LayoutParams) bottom.getLayoutParams(); param1.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM); param1.addRule(RelativeLayout.BELOW, refresh.getId()); bottom.setLayoutParams(param1);总结一下,在RelativeLayout里如果希望能用代码去控制控件的位置或者间距,记得一定要删除xml里已经设定的并且会对新增属性有影响的属性,比如在这里,如果我只增加bottom的BELOW属性,而不去除refresh的ABOVE属性,就会报错:Circular dependencies cannot exist in RelativeLayout,翻译过来就是两个控件不能循环依赖,去除其中一个依赖就可以了。