想必我们一定遇到过一个布局有很多的元素,全部显示出来又太混乱,我们能不能根据自己的需求来显示自己想要显示呢?肯定可以。要实现这一个功能,在我没有接触ViewStub标签的话,我会把不常用的元素使用INVISIBLE或者GONE进行隐藏,一些常用的使用VISIBLE显示出来。这肯定是可以的,先不说性能的问题,这样设计的话有时连自己都会弄晕。
有没有什么简单的方法呢?android给我们提供一种非常轻量级的控件,ViewStub。ViewStub虽说也是View的一种,但是它没有大小,没有绘制功能,也不参与布局,资源消耗非常低,将它放置在布局当中基本可以认为是完全不会影响性能的。下面我们又来从例子来理解它。
首先新建一个独立的布局view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="点击更多才显示"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="点击更多才显示"
/>
</LinearLayout>
在主布局activity_main.xml中:
<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:orientation="vertical"
>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="一直显示"
/>
<Button
android:id="@+id/show"
android:onClick="onClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示"
/>
<Button
android:id="@+id/unshow"
android:onClick="onClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="隐藏"
/>
<ViewStub
android:id="@+id/vs"
android:layout="@layout/view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
在这里虽然ViewStub是不占用任何空间的,但是每个布局都必须要指定layout_width和layout_height属性,否则运行就会报错。
接下来再mainActivity按钮操作
package com.example.viewstub;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
ViewStub vs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取到ViewStub控件对象
vs=((ViewStub) findViewById(R.id.vs));
}
public void onClick(View v){
if (vs != null) {
View inflatedView = vs.inflate();
//对隐藏的EditText进行操作
EditText et1 = (EditText) inflatedView.findViewById(R.id.et1);
EditText et2 = (EditText) inflatedView.findViewById(R.id.et2);
}
}
}
拿到ViewStub的实例之后,调用inflate()方setVisibility(View.VISIBLE)都可以将隐藏的布局给加载出来。
注:ViewStub所加载的布局是不可以使用merge标签的。
下面看效果图:
一开始进入效果
点击按钮后: