在Android中,对于布局的复用,一般有三种:
一种是使用用代码写自定义控件,
一种是在xml布局文件中写布局,然后在要用到相同布局的时候,使用include 来引用布局;例如:
<include
android:id="@+id/mylayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/myView1"
layout="@layout/myview_layout"
android:layout_marginTop="35dp" />
还有一种就是在xml中写好布局,然后在代码中写自定义布局的时候,使用LayoutInflater加载布局.
如:
package cn.com.cheng.layout_demo;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.RelativeLayout;
public class MyLayoutView extends RelativeLayout{
public MyLayoutView(Context context) {
this(context,null);
}
public MyLayoutView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public MyLayoutView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.myview_layout, this);
}
}