以前一直在愁xml布局中的元素多的时候看着特别麻烦,今天终于看见了一种方法能将xml分块来写并且可读性超强,就是使用include,以前估计有好多人在写,但是今天我才知道,非常喜欢这个标签,一下是我的demo,给大家献丑了!呵呵 !直接上代码吧!
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/includebutton"
layout="@layout/button"
/>
</LinearLayout>
button.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/include1"
/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/include2"
/>
</LinearLayout>
string.xml这里面就是定义string没有什么东东
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, AndroidTestinclueActivity!</string>
<string name="app_name">AndroidTestinclue</string>
<string name="include1">include1</string>
<string name="include2">include2</string>
</resources>
主Activity代码
package com.agei.include;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
* 使用include标签
* @author Agei
*
*/
public class AndroidTestinclueActivity extends Activity {
/** Called when the activity is first created. */
/**从main.xml中引入include布局,include包含的什么布局就定义什么布局***/
private LinearLayout l = null;
/***定义include.xml中的button1***/
private Button button2 = null;
/***定义include.xml中的button2***/
private Button button1 = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//找到布局,该id是main.xml中的id而不是linearlayout中的id
l = (LinearLayout) findViewById(R.id.includebutton);
//通过LinearLayout引入button1,button2
button1 = (Button) l.findViewById(R.id.button1);
button2 = (Button) l.findViewById(R.id.button2);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "button1 include", Toast.LENGTH_SHORT).show();
}
});
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "button2 include", Toast.LENGTH_SHORT).show();
}
});
}
}
代码全部完毕,以后布局就使这种方法,布局文件非常有可读性且维护起来容易!