小黑与小白的故事,通过虚拟这两个人物进行一问一答的形式来共同学习ViewStub的使用
<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="horizontal" > <Button android:id="@+id/show_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="显示"/> <ViewStub android:id="@+id/viewstub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout="@layout/sub_layout" /> <Button android:id="@+id/hide_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="隐藏"/> </LinearLayout>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ViewStub中包含的TextVeiw"/>
package com.example.viewstub; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.ViewStub; import android.view.View.OnClickListener; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ViewStub viewStub = (ViewStub) findViewById(R.id.viewstub); View showButton = findViewById(R.id.show_button); showButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { viewStub.inflate(); } }); View hideButton = findViewById(R.id.hide_button); hideButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { viewStub.setVisibility(View.GONE); } }); } }
java.lang.IllegalStateException: ViewStub must have a non-null ViewGroup viewParent at android.view.ViewStub.inflate(ViewStub.java:287) at com.example.viewstub.MainActivity$1.onClick(MainActivity.java:23) at android.view.View.performClick(View.java:4475) at android.view.View$PerformClick.run(View.java:18786) at android.os.Handler.handleCallback(Handler.java:730) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:176) at android.app.ActivityThread.main(ActivityThread.java:5419) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025) at dalvik.system.NativeStart.main(Native Method)
Android 性能优化 三 布局优化ViewStub标签的使用,布布扣,bubuko.com
Android 性能优化 三 布局优化ViewStub标签的使用
原文:http://blog.csdn.net/androiddevelop/article/details/37556307