ViewStub类延迟加载

在设计视图时,有时会考虑到某些视图的可见性是依赖于用户的操作或者运行设备的具体环境的。
此时你会如何设计?仅仅是改变View的visible属性?
我们先来看看ViewStub的介绍:
      ViewStub是一个不可见、不占空间(zero-sized)的控件,它可以用来在运行时延迟加载视图资源。只有当我们将ViewStub的可见性设为true,或者调用inflate()方法,它的视图资源才会被加载。

假设我们设计的一个页面中包含地图View,试想一下以下这种情况:
     有些用户不需要看到地图。
既然用户不需要看到地图,我们为何还坚持不懈地加载它?这反而影响了我们App的Performance。
此时,我们就可以利用ViewStub类了:
main.xml
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"  
  2.     android:layout_width"fill_parent"  
  3.     android:layout_height"fill_parent" >  
  4.   
  5.     <Button  
  6.         android:layout_width ="fill_parent"  
  7.         android:layout_height ="wrap_content"  
  8.         android:layout_gravity ="center_vertical"  
  9.         android:onClick ="onShowMap"  
  10.         android:text ="@string/show_map" />  
  11.   
  12.     <ViewStub  
  13.         android:id ="@+id/map_stub"  
  14.         android:layout_width ="fill_parent"  
  15.         android:layout_height ="fill_parent"  
  16.         android:inflatedId ="@+id/map_view"  
  17.         android:layout ="@layout/map" />  
  18. </RelativeLayout>  

map.xml
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <com.google.android.maps.MapView xmlns:android ="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width"fill_parent"  
  3.     android:layout_height"fill_parent"  
  4.     android:apiKey"my_api_key"  
  5.     android:clickable"true" />  
接下来看看MainActivity
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class MainActivity extends MapActivity {  
  2.   
  3.   private View mViewStub;  
  4.   
  5.   @Override  
  6.   public void onCreate (Bundle savedInstanceState ) {  
  7.     super. onCreate( savedInstanceState );  
  8.     setContentView( R. layout. main);  
  9.     mViewStub = findViewById( R. id. map_stub);  
  10.   }  
  11.   
  12.   public void onShowMap (View v) {  
  13.     mViewStub. setVisibility (View .VISIBLE );  
  14.   }  
  15. ....  
  16. }  

如你所见,在需要显示图像时我们才调用onShowMap来改变map_stub的可见性。在改变之前,map_stub都不会渲染加载视图资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值