/** 构造方法,初始化成员 */ public MyTopBar(Context context, AttributeSet attrs) { super(context, attrs); // 将XML中定义的自定义属性映射到attrs中。 TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.Topbar); // 从ta结构中获取数据,类似一种key,value结构,通过R.styleable.Topbar_属性名获取 mLeftTextColor = ta.getColor(R.styleable.Topbar_leftTextColor, 0); mLeftBackground = ta.getDrawable(R.styleable.Topbar_leftBackground); mLeftText = ta.getString(R.styleable.Topbar_leftText); mRightTextColor = ta.getColor(R.styleable.Topbar_rightTextColor, 0); mRightBackground = ta.getDrawable(R.styleable.Topbar_rightBackground); mRightText = ta.getString(R.styleable.Topbar_rightText); mTitleTextSize = ta.getDimension(R.styleable.Topbar_titleTextSize, 0); mTitleTextColor = ta.getColor(R.styleable.Topbar_titleTextColor, 0); mToptitle = ta.getString(R.styleable.Topbar_toptitle); // 进行垃圾回收 ta.recycle(); setBackgroundColor(getResources().getColor(R.color.colorPrimary)); // 设置View的背景颜色 // 初始化控件 mBtnLeft = new TopBarButton(context); mBtnRight = new TopBarButton(context); mTvTitle = new TextView(context); // 设置控件的值 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mBtnLeft.setBackground(mLeftBackground); mBtnRight.setBackground(mRightBackground); } else { mBtnLeft.setBackground(mLeftBackground); mBtnRight.setBackground(mRightBackground); } mBtnRight.setTextColor(mRightTextColor); // 设置文字颜色 mBtnRight.setText(mRightText); // 设置文本 mTvTitle.setTextColor(mTitleTextColor); // 设置字体颜色 mTvTitle.setTextSize(mTitleTextSize); // 设置字体大小 mTvTitle.setText(mToptitle); // 设置文本 mTvTitle.setGravity(Gravity.CENTER); // 居中显示 // 设置左边布局属性的width和height mLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); // 设置对齐方式为父容器的左侧 mLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE); // 将左边按钮添加到视图中,并设置布局属性 addView(mBtnLeft, mLayoutParams); // 设置右边布局属性的width和height mRightParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); // 设置对齐方式为父容器的右侧 mRightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE); // 将右边按钮添加到视图中,并设置布局属性 addView(mBtnRight, mRightParams); // 设置中间布局属性的width和height mTitleParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); // 设置对齐方式为居中对齐 mTitleParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE); // 将中间TextView添加到视图中,并设置布局属性 addView(mTvTitle, mTitleParams); // 添加左侧按钮的Click事件 mBtnLeft.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { listener.leftClick(); } }); // 添加右侧按钮的Click事件 mBtnRight.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { listener.rightClick(); } }); }