Android实战经验之Incude便签

来源:互联网 发布:mac safari关闭标签 编辑:程序博客网 时间:2024/05/16 09:09
 

当我们做项目时经常会用到相同的布局设计,如果都写在一个xml文件中,代码显得很冗余,,让人有一种去死的感觉,可读性也很差。

所以我们可以把相同布局的代码单独拿出来放在一个xml文件中,通过<include /> 标签来重用它。这样我们的代码显得比较清洁,一目了然。

读者对代码的整体布局有一个深入的了解。

1 include标签只有layout属性是必须的
2.include标签若指定了ID属性,而你的layout也定义了ID,则你的layout的ID会被覆盖 

3 在include标签中所有的android:layout_*都是有效的。

但前提是必须要写layout_width和layout_height两个属性,否则无效 。

看一个例子:

main.xml

1
2
3
4
5
6
7
8
9
10
11
<?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

1
2
3
4
5
6
7
8
9
10
11
12
<?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

1
2
3
4
5
6
7
8
9
10
11
12
13
package xiaosi.include;
  
import android.app.Activity;
import android.os.Bundle;
  
public class IncludeActivity extendsActivity {
    /** Called when the activity is first created. */
    @Override
    publicvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

 

原创粉丝点击