本文讲述的自定义的组合控件,实现类似于iPhone的导航栏效果,在导航栏左侧有一个返回按钮,中间是界面的标题,右边是点击的按钮。
(1)第一种方法:
1、新建title.xml布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#bbb" >
<Button
android:id="@+id/title_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:background="#fff"
android:text="Back"
android:textColor="#ccc" />
<TextView
android:id="@+id/title_text"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:text="Title Text"
android:textColor="#ccc"
android:textSize="24sp" />
<Button
android:id="@+id/title_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:background="#fff"
android:text="Edit"
android:textColor="#ccc" />
</LinearLayout>
2、在main_activity.xml中,通过标记来包含title布局。
<include layout="@layout/title" />
(2)第二种方法
1、新建自定义控件类:TitleLayout,继承自LinearLayout
package com.example.customview;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
/**
* 自定义的控件
* @author w8
*
*/
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
LayoutInflater.from(context).inflate(R.layout.title, this);
}
}
在TitleLayout构造方法中,我们通过LayoutInflater来动态加载title布局。
2、在activity_main.xml中修改布局文件,注意需要指定完整的控件类名。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- 加载自定义的控件,跟普通控件相比,需要指明完整的类名 -->
<com.example.customview.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</com.example.customview.TitleLayout>
</LinearLayout>