合理使用weightSum 属性和layout_weight 属性
比例式的布局好处在于对于不同大小的界面,它的大小随之变化,非常灵活,使用较为简单:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="horizontal"
android:weightSum="1"
tools:context="com.example.administrator.androidbase.one.WeightSumActivity">
<Button
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_weight="0.5"
android:gravity="center"
android:text="宽度固定为父布局一半"/>
</LinearLayout>
使用<include /> 标签避免代码重复
<include />在项目中很常见,例如界面头部标题等一些常用界面。自定义view也是可以,但是当只是固定纯界面展示时,<include />无疑更为方便。
<RelativeLayout
android:id="@+id/topMenu"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<include
layout="@layout/top_layout" />
</RelativeLayout>
通过ViewStub 实现View 的延迟加载
在应用界面中有的功能界面需要用户使用时才会由点击后出现,如果通过设置
setVisibility也是可以实现,但是这样在界面初始化时,系统会初始化这部分隐藏的界面,如果用户并未使用这些界面,就造成了内存资源的浪费,而ViewStub的好处在于它是一种预留界面的方式,当你初次设置显示时才开始构建界面,占用内存资源,当然之后也是通过setVisibility设置显隐。
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.androidbase.one.ViewStubActivity">
<Button
android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Show Map" />
<ViewStub
android:id="@+id/stub"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/show"
android:layout_centerInParent="true"
android:inflatedId="@+id/hole_world_id"
android:layout="@layout/hole_world" />
</RelativeLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_stub);
findViewById(R.id.show).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (findViewById(R.id.hole_world_id)==null)
//这时才开始构建布局
findViewById(R.id.stub).setVisibility(View.VISIBLE);
}
});
}
特别注意界面构建后,ViewStub应该是销毁了,因为此时findViewById(R.id.sub)为null,所以我加了个判断隐藏布局是否构建,这里的hole_world_id 就是隐藏view的id