相信大家看过我上面一篇转载的
自定义控件之——标题栏
的小伙伴们对自定义标题栏 已经有一定程度的了解了。此处我想把自己项目中亲手做的一个既可以在xml中设置标题名称属性,又可以在代码中直接引用设置标题栏的名称的自定义标题栏Demo记录下来,以便后面当做笔记查阅。
1.设置xml布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<TextView
android:id="@+id/tv_titlebar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="登录"
android:textColor="@color/color_af0000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="15sp" />
<ImageView
android:id="@+id/img_login_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="@drawable/back" />
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="0.8dp"
android:layout_alignParentBottom="true"
android:background="#ccc"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
</RelativeLayout>
2.在attr.xml文件中设置需要改变的属性
<declare-styleable name="CustomTitleBar">
<attr name="titleText" format="string"/>
</declare-styleable>
3.自定义CustomTitleBar 类:
public class CustomTitleBar extends RelativeLayout
{
private String titleText;
private ImageView back;
private TextView title;
public CustomTitleBar(Context context)
{
super(context);
}
public CustomTitleBar(Context context, AttributeSet attrs)
{
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.custom_titlebar, this);
back = (ImageView) findViewById(R.id.img_login_back);
title = (TextView) findViewById(R.id.tv_titlebar);
back.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
((Activity)getContext()).finish();
}
});
//获得自定义属性并赋值
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomTitleBar);
titleText = typedArray.getString(R.styleable.CustomTitleBar_titleText);
}
public void setTextContent(String test)
{
titleText= test ;
title.setText(titleText);
}
}
4.在代码中使用
<pre name="code" class="html">CustomTitleBar <span style="font-family: Arial, Helvetica, sans-serif;">custom_titlebar = (CustomTitleBar) findViewById(R.id.custom_titlebar);</span>
custom_titlebar.setTextContent("");
5.在布局中使用
<com.example.custom.CustomTitleBar
android:id="@+id/custom_titlebar"
android:layout_width="match_parent"
android:layout_height="40dp"
custom:titleText=""
android:layout_alignParentTop="true">
</com.example.custom.CustomTitleBar>