当我们做项目时经常会用到相同的布局设计,如果都写在一个xml文件中,代码显得很冗余,,让人有一种去死的感觉,可读性也很差。
所以我们可以把相同布局的代码单独拿出来放在一个xml文件中,通过<include /> 标签来重用它。这样我们的代码显得比较清洁,一目了然。
读者对代码的整体布局有一个深入的了解。
1 include标签只有layout属性是必须的
2.include标签若指定了ID属性,而你的layout也定义了ID,则你的layout的ID会被覆盖
3 在include标签中所有的android:layout_*都是有效的。
但前提是必须要写layout_width和layout_height两个属性,否则无效 。
看一个例子:
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" >
- <include
- android:id="@+id/include"
- layout="@layout/other" />
- </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/include"
layout="@layout/other" />
</LinearLayout>
include要引用的那个xml:other.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" >
- <ImageView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:src="@drawable/free_bg_small_3" />
- </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" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/free_bg_small_3" />
</LinearLayout>
IncludeActivity.java
- package xiaosi.include;
- import android.app.Activity;
- import android.os.Bundle;
- public class IncludeActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
- }
package xiaosi.include;
import android.app.Activity;
import android.os.Bundle;
public class IncludeActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}