Android学习(十七)自定义View控件 TopBar


一、创建自定义TopBar头部菜单条

  实现步骤:

  1、在values中添加attrs.xml文件,设置自定义属性。

  2、添加Topbar类,继承RelativeLayout,实现具体功能。

  3、添加到页面上,并设置添加事件。

 

参考代码:

  values\attrs.xml

复制代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Topbar">
    <attr name="toptitle" format="string" />                           <!--中间文字,类型字符串-->
    <attr name="titleTextSize" format="dimension" />                   <!--字体大小,类型为数字-->
    <attr name="titleTextColor" format="color"/>                       <!--字体颜色,类型为颜色-->
    <attr name="leftTextColor" format="color"/>                        <!--左侧字体颜色,类型为颜色-->
    <attr name="leftBackground" format="reference|color" />            <!--左侧背景颜色,类型为图片和颜色-->
    <attr name="leftText" format="string" />                           <!--左侧文字-->
    <attr name="rightTextColor" format="color"/>                       <!--右侧文字颜色-->
    <attr name="rightBackground" format="reference|color" />           <!--右侧背景-->
    <attr name="rightText" format="string" />                          <!--右侧文字-->
</declare-styleable>
</resources>
复制代码

 

  TopBar.java,自定义View实现类。

复制代码
package com.example.zhengcheng.myapplication;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * Created by zhengcheng on 2015/4/11.
 */
public class TopBar extends RelativeLayout {
    private Button btn_left, btn_right;
    private TextView tv_title;

    private int leftTextColor;
    private Drawable leftBackground;
    private String leftText;

    private int rightTextColor;
    private Drawable rightBackground;
    private String rightText;

    private float titleTextSize;
    private int titleTextColor;
    private String toptitle;

    //定义三个布局参数
    private LayoutParams leftParams, rightParams, titleParams;

    //定义一个事件接口
    public interface topbarClickListener{
        public void leftClick();
        public void rightClick();
    }

    //创建接口对象
    public topbarClickListener listener;

    //创建为事件接口赋值的方法
    public void setOnTopBarClickListener(topbarClickListener listener){
        this.listener = listener;
    }

    //构造方法,初始化成员
    public TopBar(Context context, AttributeSet attrs) {
        super(context, attrs);

        //将XML中定义的自定义属性映射到attrs中。
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.Topbar);

        //从ta结构中获取数据,类似一种key,value结构,通过R.styleable.Topbar_属性名获取
        leftTextColor = ta.getColor(R.styleable.Topbar_leftTextColor, 0);
        leftBackground = ta.getDrawable(R.styleable.Topbar_leftBackground);
        leftText = ta.getString(R.styleable.Topbar_leftText);

        rightTextColor = ta.getColor(R.styleable.Topbar_rightTextColor, 0);
        rightBackground = ta.getDrawable(R.styleable.Topbar_rightBackground);
        rightText = ta.getString(R.styleable.Topbar_rightText);

        titleTextSize = ta.getDimension(R.styleable.Topbar_titleTextSize, 0);
        titleTextColor = ta.getColor(R.styleable.Topbar_titleTextColor, 0);
        toptitle = ta.getString(R.styleable.Topbar_toptitle);

        //进行垃圾回收
        ta.recycle();

        //初始化控件
        btn_left = new Button(context);
        btn_right = new Button(context);
        tv_title = new TextView(context);

        //设置控件的值
        btn_left.setTextColor(leftTextColor);          //设置文字颜色
        btn_left.setBackground(leftBackground);        //设置背景
        btn_left.setText(leftText);                    //设置文本

        btn_right.setTextColor(rightTextColor);        //设置文字颜色
        btn_right.setBackground(rightBackground);      //设置背景
        btn_right.setText(rightText);                  //设置文本

        tv_title.setTextColor(titleTextColor);         //设置字体颜色
        tv_title.setTextSize(titleTextSize);           //设置字体大小
        tv_title.setText(toptitle);                    //设置文本
        tv_title.setGravity(Gravity.CENTER);           //居中显示

        setBackgroundColor(0xfff59563);               //设置View的背景颜色

        //设置布局属性的width和height
        leftParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        //设置对齐方式为父容器的左侧
        leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
        //将左边按钮添加到视图中,并设置布局属性
        addView(btn_left, leftParams);

        //设置布局属性的width和height
        rightParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        //设置对齐方式为父容器的右侧
        rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
        //将右边按钮添加到视图中,并设置布局属性
        addView(btn_right, rightParams);

        //设置布局属性的width和height
        titleParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        //设置对齐方式为居中对齐
        titleParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
        //将中间TextView添加到视图中,并设置布局属性
        addView(tv_title, titleParams);

        //添加左侧按钮的Click事件
        btn_left.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.leftClick();
            }
        });

        //添加右侧按钮的Click事件
        btn_right.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.rightClick();
            }
        });
    }

    /**
     * 设置左边按钮是否隐藏,true隐藏, false消失
     * @param flag
     */
    public void setLeftButtonIsVisiable(boolean flag){
        if(flag){
            btn_left.setVisibility(View.VISIBLE);
        }else{
            btn_left.setVisibility(View.GONE);
        }
    }

    /**
     * 设置右边按钮是否隐藏,true隐藏, false消失
     * @param flag
     */
    public void setRightButtonIsVisiable(boolean flag){
        if(flag){
            btn_right.setVisibility(View.VISIBLE);
        }else{
            btn_right.setVisibility(View.GONE);
        }
    }
}
复制代码

 

  main.xml,主页面文件

复制代码
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <com.example.zhengcheng.myapplication.TopBar
        android:id="@+id/MyTopbar"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        custom:leftTextColor="#FFFFFF"
        custom:leftText="Back"
        custom:leftBackground="#ffa4c161"
        custom:rightTextColor="#FFFFFF"
        custom:rightText="More"
        custom:rightBackground="#ffa4c161"
        custom:titleTextSize="8dp"
        custom:titleTextColor="#000000"
        custom:toptitle="自定义模版">
    </com.example.zhengcheng.myapplication.TopBar>
</RelativeLayout>
复制代码

 

  main.java 后台代码文件

复制代码
package com.example.zhengcheng.myapplication;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TopBar topbar = (TopBar) findViewById(R.id.MyTopbar);

        //设置左右按钮为隐藏
        topbar.setLeftButtonIsVisiable(false);
        topbar.setRightButtonIsVisiable(false);

        //添加topbar的事件
        topbar.setOnTopBarClickListener(new TopBar.topbarClickListener() {
            @Override
            public void leftClick() {
                Toast.makeText(MainActivity.this,"点击了左边的按钮",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void rightClick() {
                Toast.makeText(MainActivity.this,"点击了右边的按钮",Toast.LENGTH_SHORT).show();
            }
        });
    }
}
复制代码

 

  全部功能实现,可以使某个功能模块重复利用。大大提高代码的福永率,有点类似.net中的用户控件!


猜你喜欢

转载自blog.csdn.net/u010507199/article/details/46294781