viewstub 布局加载时性能优化 2 demo

先看layout文件:

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/test_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="test" />

    <ViewStub
        android:id="@+id/viewstub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout="@layout/mylayout" />
    
     <Button
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="test1" />

</LinearLayout>


mylayout.xml 这个文件是viewstub要延时加载的,里面就放了一个开关

<?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" >

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToggleButton" />

</LinearLayout>


源代码:

package com.gxq.testgridlayout;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.widget.Button;

public class MainActivity extends Activity {

	private Button mTestBtn;
	private ViewStub mViewStub;
	private View mView;

	private OnClickListener mOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			//取出ViewStub里的mylayout放在mView里
			//这个是等到需要是才放进布局的,就是延迟加载啦 啦啦啦
			if(mView == null){
				mView = mViewStub.inflate();
			}
			
			//若当前显示,则隐藏,否则,显示
//			isShown(): True if this view and all of its ancestors are VISIBLE
			boolean isShow = mView.isShown();
			Log.d("test", "isShow : " + isShow);
			if (isShow) {
				mView.setVisibility(View.GONE);
			} else {
				mView.setVisibility(View.VISIBLE);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		//通过test这个btn来触发ViewStub里的mylayout的显示与否
		mTestBtn = (Button) this.findViewById(R.id.test_btn);
		mTestBtn.setOnClickListener(mOnClickListener);

		//ViewStub
		mViewStub = (ViewStub) findViewById(R.id.viewstub);
	}
}


结果:

第一次test Button按下后:

viewstub 布局加载时性能优化 2 demo_第1张图片

第二次test Button按下后:

viewstub 布局加载时性能优化 2 demo_第2张图片

代码下载链接:

http://download.csdn.net/detail/null1989/6446067

你可能感兴趣的:(viewstub 布局加载时性能优化 2 demo)