Android布局优化
使用标签来合并布局
当父布局是FrameLayout的时候,我们就可以用这个标签将我们自己的父布局和系统Activity提供的视图FrameLayout进行合并,这样就会减少一层布局嵌套
使用时直接将FrameLayout替换成标签即可
使用标签重用布局
使用场景
多次使用相同的布局
布局有一个通用的组成部分
布局依赖于设备配置比如横竖屏切换
使用方式:代码也很简单创建将要被重用的布局children.xml;然后在想要重用children.xml的地方引入:
<include android:id="@+id/inLayout"
android:layout="@layout/children">
ViewStub
ViewStub采用了推迟初始化技术,它可以推迟实例化提高性能,并且如果不触发初始化的话就不会初始化会节省这部分的内存
ViewStub是一个轻量级不可见的视图。
使用:
<FrameLayout 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"
tools:context="com.android.test.TestAnsyActivity">
<ViewStub
android:id="@+id/mystub"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout="@layout/stub_layout" />
如代码所示,布局被展开时,只有一个子视图mystub,mystub引用了一个布局stub_layout,即使stub_layout很复杂展开很费时间都没关系,都不会影响视图的展开效率,因为此时stub_layout布局无需展开.
那怎么展开ViewStub布局呢
方式一:
ViewStub stub = (ViewStub) findViewById(R.id.mystub);
View inflatedView = stub.inflate();
方式二:
View view = findViewById(R.id.mystub);
view.setVisibility(View.VISIBLE);
view = findViewById(R.id.myid);
不过,尽可能的减少findViewById()的使用,如下:
View view = findViewById(R.id.mystub);
view.setVisibility(View.VISIBLE);
if (view.getParent() == null) {
view = findViewById(R.id.myid);
} else {
}