在一个项目中我们可能会需要用到相同的布局设计,如果都写在一个xml文件中,代码显得很冗余,并且可读性也很差,所以我们可以把相同布局的代码单独写成一个模块,然后用到的时候可以通过<include /> 标签来重用layout代码。
btn.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="wrap_content"
-
android:orientation="vertical" >
-
<Button
-
android:id="@+id/btn"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"
-
android:text="Button">
-
</Button>
- </LinearLayout>
-
<?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"
-
>
-
<include android:id="@+id/in1" layout="@layout/btn"/>
-
<include android:id="@+id/in2" layout="@layout/btn"/>
-
<TextView android:id="@+id/tv"
-
android:layout_width="fill_parent"
-
android:layout_height="wrap_content"
-
android:text="@string/hello" />
- </LinearLayout>
-
package com.hilary;
-
-
import android.app.Activity;
-
import android.graphics.Color;
-
import android.os.Bundle;
-
import android.view.View;
-
import android.view.View.OnClickListener;
-
import android.widget.Button;
-
import android.widget.LinearLayout;
-
import android.widget.TextView;
-
-
import com.hialry.R;
-
/**
-
*
-
*@author:hilary
-
*@Date:2011-12-8
-
*@description:
-
*
-
**/
-
public class TestActivity extends Activity {
-
private TextView tv = null;
-
private LinearLayout ll = null;
-
private LinearLayout ll2 = null;
-
-
/** Called when the activity is first created. */
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
tv = (TextView) findViewById(R.id.tv);
-
//如果一个布局文件中包含同一个xml文件,这两个xml中的控件Id是一样的,当需要操作这些控件时,需要通过定义这两个View来加以区分,
-
//如果就包含同一个xml文件侧不需要此步操作
-
ll = (LinearLayout) findViewById(R.id.in1);
-
ll2 = (LinearLayout) findViewById(R.id.in2);
-
-
ll.setBackgroundColor(Color.RED);
-
-
Button btn = (Button) ll.findViewById(R.id.btn);
-
btn.setOnClickListener(new OnClickListener() {
-
-
@Override
-
public void onClick(View v) {
-
tv.setText("My name is hilary");
-
}
-
});
-
-
Button btn2 = (Button) ll2.findViewById(R.id.btn);
-
btn2.setOnClickListener(new OnClickListener() {
-
-
@Override
-
public void onClick(View v) {
-
tv.setText(" You select second Button!");
-
-
}
-
});
-
}
- }