课程链接:http://www.imooc.com/learn/247
实现自定义Topbar可以大略分为如下三个步骤:
步骤1:定义atts.xml属性文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Topbar">
<attr name="title" format="string"/>
<attr name="titleTextSize" format="dimension"/>
<attr name="titleTextColor" format="color"/>
<attr name="leftText" format="string"/>
<attr name="leftBackground" format="referencecolor"/>
<attr name="leftTextColor" format="color"/>
<attr name="rightText" format="string"/>
<attr name="rightBackground" format="referencecolor"/>
<attr name="rightTextColor" format="color"/>
</declare-styleable>
</resources>
步骤2:继承RelativeLayout,实现Topbar
public class Topbar extends RelativeLayout{
private Button leftButton,rightButton;
private TextView tvTitle;
// 左边button的属性
private int leftTextColor;
private Drawable leftBackground;
private String leftText;
// 右边button的属性
private int rightTextColor;
private Drawable rightBackground;
private String rightText;
// Title属性
private float titleTextSize;
private int titleTextColor;
private String title;
private LayoutParams leftParams,rightParams,titleParams; // 布局参数对象
public Topbar(Context context, AttributeSet attrs) {
super(context, attrs);
// 获取自定义的属性
TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.Topbar);
// 实例化属性成员
titleTextSize=ta.getDimension(R.styleable.Topbar_titleTextSize, 0);
titleTextColor=ta.getColor(R.styleable.Topbar_titleTextColor, 0);
title=ta.getString(R.styleable.Topbar_title);
// 省略实例化其他属性成员的代码...
ta.recycle(); // 回收数据,避免资源浪费
// 根据context实例化控件
tvTitle=new TextView(context);
leftButton=new Button(context);
rightButton=new Button(context);
// 为属性成员赋值
tvTitle.setTextSize(titleTextSize);
tvTitle.setTextColor(titleTextColor);
tvTitle.setText(title);
tvTitle.setGravity(Gravity.CENTER); // 设置TextView文字居中显示
// 省略其他属性成员的赋值代码...
setBackgroundColor(0xFFF59563); // 给当前的Topbar设置背景颜色
// 实例化布局参数对象,另两个布局参数对象的实例化类似,这里省略
titleParams=new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT);
// 为控件添加布局属性,省略另两个控件的类似操作
titleParams.addRule(RelativeLayout.CENTER_IN_PARENT,TRUE);
// 将控件添加到Topbar并传入对应的布局参数对象
addView(tvTitle, titleParams);
addView(leftButton, leftParams);
addView(rightButton, rightParams);
}
}
步骤3:在布局文件使用自定义的Topbar
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom = "http://schemas.android.com/apk/res-auto" <!-- 设置自定义属性的命名空间 -->
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.imooc.widget.Topbar
android:layout_width="match_parent"
android:layout_height="50dp"
<!-- 使用自定义属性 -->
custom:leftBackground="@drawable/button_selector"
custom:leftText="BACK"
custom:leftTextColor="@color/white"
custom:rightBackground="@drawable/button_selector"
custom:rightText="MORE"
custom:rightTextColor="@color/white"
custom:title="自定义标题"
custom:titleTextColor="#123412"
custom:titleTextSize="15sp">
</com.imooc.widget.Topbar>
</RelativeLayout>