Android include使用

2023-06-12,,

安卓中,布局include主要是重用布局作用,当一个界面配置较多情况下,采用include可以大大增强  其可读性。

eg:主布局include一个layout01布局,layout01布局中include一个layout02布局。

//layout01.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="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnLayout01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="This btn lies on layout01" />

    <include layout="@layout/layout02" />

</LinearLayout>

//layout02.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="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnLayout02"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="This btn lies on layout02" />


</LinearLayout>

//activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >
    <TextView
        android:id="@+id/tvShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This txextview lies on main layout" />
    <include
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tvShow"
        layout="@layout/layout01" />
</RelativeLayout>

//MainActivity.java

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Button btnLayout01 = (Button)findViewById(R.id.btnLayout01);
		Button btnLayout02 = (Button)findViewById(R.id.btnLayout02);

		btnLayout01.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("layout01","btn01 click");
			}
		});
		btnLayout02.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("layout02","btn02 click");
			}
		});
	}
}

注:采用include方法,可直接认为包含(内嵌)的界面就是直接写在当前布局文件中的。所以,对于包含(include)进来的界面中的控件,可直接用findViewById()方法找到当中的子控件。

from:http://blog.csdn.net/xyz_lmn/article/details/14524567

 1)<include />标签可以使用单独的layout属性,这个也是必须使用的。

 2)可以使用其他属性。<include />标签若指定了ID属性,而你的layout也定义了ID,则你的layoutID会被覆盖,解决方案。

 3)在include标签中所有的android:layout_*都是有效的,前提是必须要写layout_widthlayout_height两个属性

 4)布局中可以包含两个相同的include标签,引用时可以使用如下方法解决(参考):

《Android include使用.doc》

下载本文的Word格式文档,以方便收藏与打印。