自定义View之TitleBar

来源:互联网 发布:python主要应用领域 编辑:程序博客网 时间:2024/05/21 10:25

一般应用都会有顶部标题栏,上面会有标题,左侧返回按钮,右侧功能按钮,在v7包中有ActionBar控件可以实现,这里记录下,自己定义个布局,简单实现下功能。

  • 自定义布局 title_bar.xml

    一般应用都会有顶部标题栏,上面会有标题,左侧返回按钮,右侧功能按钮,在v7包中有ActionBar控件可以实现,这里记录下,自己定义个布局,简单实现下功能。
  • 自定义布局 title_bar.xml

    <RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="45dp"    android:background="#fff" >    <ImageButton        android:id="@+id/title_back"        android:layout_width="40dp"        android:layout_height="40dp"        android:layout_centerVertical="true"        android:background="@null"        android:src="@drawable/title_btn_selector" />    <TextView        android:id="@+id/title_content"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="设置"        android:textSize="20sp" />    <ImageButton         android:id="@+id/title_function"        android:layout_width="40dp"        android:layout_height="40dp"        android:src="@drawable/chat_member"        android:layout_alignParentRight="true"        android:layout_centerVertical="true"        android:visibility="gone"        />    <View         android:layout_width="match_parent"        android:layout_height="0.5dp"        android:background="@android:color/darker_gray"        android:layout_alignParentBottom="true"        />

  • 在attr.xml中添加你需要设置的属性

    <declare-styleable name="TitleBar">    <attr name="right_img" format="reference" />    <attr name="title" format="string" /></declare-styleable>    
  • 自定义TitleBar类

    主要实现的构造方法 attrs该形参中有在xml文件中配置的各种属性,可以拿到每个属性的值。获取所需的属性值public TitleBar(Context context, AttributeSet attrs) {    super(context, attrs);    res = attrs.getAttributeResourceValue(NAMESPACE, "right_img", -1);    title = attrs.getAttributeValue(NAMESPACE, "title");    initView();    int attributeCount = attrs.getAttributeCount();    for (int i = 0; i < attributeCount; i++) {        String attributeName = attrs.getAttributeName(i);        String attributeValue = attrs.getAttributeValue(i);        System.out.println(attributeName + "=" + attributeValue);    }}创建initView()方法,初始化title_bar.xml中的各个控件private void initView() {    View view = View.inflate(getContext(), R.layout.title_view, this);    backImg = (ImageView) view.findViewById(R.id.title_function);    tvTitle = (TextView) view.findViewById(R.id.title_content);    if (res > -1) {        backImg.setImageResource(res);        backImg.setVisibility(View.VISIBLE);    }    tvTitle.setText(title);}
  • 最后可以添加一个接口回调,用于左侧按钮与右侧按钮的点击事件

    在图片点击事件的回调方法中调用该接口的方法,对外界开发一个setlistener的方法public interface OnTitleBarClickListener{    public void titleBarback();    public void titleBarRightMenu();}
0 0
原创粉丝点击