Android UI (include的使用)


如果在一个项目中需要用到相同的布局设计,可以通过<include /> 标签来重用layout代码,以下是我总结的使用<include /> 标签来重用layout代码的方法:


首先:定义公共的layout:testlayout.xml


<?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="wrap_content"
    android:layout_gravity="left"
    android:orientation="vertical"
    >
    <TextView android:id="@+id/tv_1"  
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="aaaaaaaaaaaaa"
        android:textSize="24sp"
        
        />

    <TextView android:id="@+id/tv_2"  
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="bbbbbbbbbbb"
        android:textSize="24sp"
        
        />
    
    <TextView android:id="@+id/tv_3"  
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="cccccccccccccc"
        android:textSize="24sp"
        
        />
</LinearLayout>

 

再次,我们定义调用的xml:main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <include
        android:id="@+id/include_1"
        layout="@layout/testlayout" />

    <include
        android:id="@+id/include_2"
        layout="@layout/testlayout" />

    <include
        android:id="@+id/include_3"
        layout="@layout/testlayout" />

        <!--     <include layout="@layout/testlayout"/>
     -->
    
    
    </LinearLayout>

 

最后就是在代码中对其中组件的使用了:


如果我们只include“一次“ 公用的testlayout.xml ,则直接获取其中的组件即可改变其值:


 TextView  test = (TextView) findViewById(R.id.tv_1);
  test.setText("testtext");

 

如果我们只include“多次“ 公用的testlayout.xml (比如示例代码中),则不能 直接获取其中的组件改变其值:

例如我们要修改第三个include标签中textview的值,代码如下:

View view3 =  findViewById(R.id.include_3);
TextView  test = (TextView) view3.findViewById(R.id.tv_1);
test.setText("testtext");

这样我们就可以对其中各个include的layout组件的值进行修改。






猜你喜欢

转载自test-angel.iteye.com/blog/1738257