HackTwo

使用延迟加载以及避免代码重复
​一.概要:
    <include />标签是整理布局的有效工具,提供了合理组织XML布局文件的有效方法。
    ViewStub是实现延迟加载视图的优秀类。无论在什么情况下,只要开发者需要根据上下文选择隐藏或则显示一个视图,都可以使用ViewSub实现。
    或许并不会因为一个视图的延迟加载而感觉到性能的明显提升,但是如果视图树的层次很深,便会感觉到性能上的 差距了。
二.代码:
  main.xml
 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 
19     <include
20         android:layout_width="fill_parent"
21         android:layout_height="wrap_content"
22         android:layout_alignParentBottom="true"
23         android:layout_marginBottom="30dp"
24         layout="@layout/footer" />
25 
26 </RelativeLayout>

  footer.xml

1 <?xml version="1.0" encoding="utf-8"?>
2 <TextView xmlns:android="http://schemas.android.com/apk/res/android"
3     android:layout_width="0dp"
4     android:layout_height="0dp"
5     android:gravity="center"
6     android:text="@string/footer_text" />

  MainActivity

 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   @Override
17   protected boolean isRouteDisplayed() {
18     return false;
19   }
20 }

  Ps:对于<include />中用到的android:layout_width和android:layout_height的属性在被引用的布局文件中要申明为0;

   
posted @ 2014-10-27 16:17  perfect亮  阅读(161)  评论(0编辑  收藏  举报