使用include实现布局(layout)复用

来源:互联网 发布:剑三淘宝cos店铺 编辑:程序博客网 时间:2024/05/05 03:11

 假使我们遇到这么一种情况,我们需要开发一个app,这个app的基本所有的Activity都使用到了相同的布局,我们该如何设计?我们是给这些个Activity布局文件都统一加上一样的布局代码吗?但是这样维护起来很麻烦,修改很不方便,Android布局中有没有一种类似于编程语言的include语法呢?答案是有的,但是sdk的demo并没有说出使用方法,但这并不说明不好使用,其实很简单。下面的IncludeXmlTest工程给出了样式。

        我们新建一个IncludeXmlTest工程,我们先从布局文件上下手,我们新建一个真正的real.xml文件,来实现我们的布局,代码如下:

XML/HTML代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <Button  
  8.         android:id="@+id/button"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="show" />  
  12.   
  13.     <TextView  
  14.         android:id="@+id/text"  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="" />  
  18.   
  19. </LinearLayout>  

        然后在我们需要引入的xml文件中,include这个real.xml就可以了,我这个main.xml代码如下:

XML/HTML代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.    <include   
  8.        android:id="@+id/include"  
  9.        layout="@layout/real"/>  
  10.   
  11. </LinearLayout>  

        这个include部分就是引入了real.xml的布局,之后我们在程序中只需要布局main.xml文件即可:

Java代码
  1. public class IncludeXmlTestActivity extends Activity {  
  2.     private TextView mTextView;  
  3.     private Button mButton;  
  4.       
  5.     /** Called when the activity is first created. */  
  6.     @Override  
  7.     public void onCreate(Bundle savedInstanceState) {  
  8.         super.onCreate(savedInstanceState);  
  9.         setContentView(R.layout.main);  
  10.           
  11.         initView();  
  12.     }  
  13.       
  14.     /** 
  15.      * 设置view 
  16.      * */  
  17.     public void initView(){  
  18.         mTextView = (TextView) findViewById(R.id.text);  
  19.         mButton = (Button)findViewById(R.id.button);  
  20.         mButton.setOnClickListener(new OnClickListener() {  
  21.               
  22.             @Override  
  23.             public void onClick(View v) {  
  24.                 // TODO Auto-generated method stub  
  25.                 mTextView.setText("hello, i am here");  
  26.             }  
  27.         });  
  28.     }  
  29. }  

        怎么样简单吧,大家在重复布局的时候一定要记住使用哦,最后看下运行效果:

运行程序

点击按钮,显示textView的文字