我是Android开发的新手。
我从https://developer.android.com/training/improving-layouts/loading-ondemand.html了解到ViewStub。
它提到使用ViewStub更加经济实惠,占用内存更少。
以下是我的代码:
MainLayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Layout1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:background="@color/blue"
android:orientation="vertical" >
.....
.....
<Button android:id="@+id/ShowBackground"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
<Button android:id="@+id/ShowBackground2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="@string/title_close" />
<View
android:id="@+id/ShowView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/blue" />
<ViewStub
android:id="@+id/ShowViewStub"
android:layout="@layout/test"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
</RelativeLayout>
test.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ShowViewLayout"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:background="@color/blue_dimmer"
android:orientation="vertical" >
</RelativeLayout>
主活动:
private ViewStub mViewStub;
private View mView;
private Button mBackground1;
private Button mBackground2
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.MainLayout);
mView = (ViewStub) findViewById(R.id.ShowView);
mViewStub = (ViewStub) findViewById(R.id.ShowViewStub);
mBackground1 = (Button)this.findViewById(R.id.ShowBackground);
mBackground1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mView.setVisibility(View.VISIBLE);
}
});
}
mBackground2 = (Button)this.findViewById(R.id. ShowBackground2);
mBackground2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mViewStub.setVisibility(View.VISIBLE);
}
});
}
问题:
View和ViewStub在MainActivity中表现良好。
我知道ViewStub适用于很少使用的视图。如果在MainActivity中至少调用1次ViewStub,那么由于test.xml布局被添加到活动中,不应该有更多的内存使用吗?
我所看到的是ViewStub始终可见,除非它被调用View.Gone....
请问有人能解释一下这两者之间的区别吗?
非常感谢您的帮助,
谢谢。