首先可以先写一个xml文件将整体的样式写在里面,方便调用,起名叫attr.xml放在res/values目录下
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name = "Topbar">
<attr name="title" format="string"></attr>
<attr name="titleTextSize" format="dimension"></attr>
<attr name="titleTextColor" format="color"></attr>
<attr name="leftTextColor" format="color"></attr>
<attr name="leftBackground" format="reference|color"></attr>
<attr name ="rightTextColor" format="color"/>
</declare-styleable>
</resources>
第二步,写一个类继承RelativeLayout,生成相应部件
package com.example.myviewtext;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MyRelativeLayout extends RelativeLayout {
//声明这个布局里的控件
private Button leftButton,righButton;
private TextView titleTextView;
//定义按钮的背景
private int leftBackground;
private Drawable leftDrawable;
private String leftText;
//定义标题的属性
private float titleTextSize;
private int titleColor;
private String titleText;
//内部控件布局属性
private LayoutParams leftParams,titleParams;
@SuppressLint("NewApi")
public MyRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
//获取xml中的值
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.Topbar);
leftBackground = typedArray.getColor(R.styleable.Topbar_leftTextColor, Color.BLACK);//第二个参数是默认值
leftDrawable = typedArray.getDrawable(R.styleable.Topbar_leftBackground);
titleTextSize = typedArray.getDimension(R.styleable.Topbar_titleTextSize, 20f);
//释放缓存
typedArray.recycle();
//实例化内部view
leftButton = new Button(context);
titleTextView = new TextView(context);
//给内部view设置属性
leftButton.setTextColor(Color.WHITE);
leftButton.setBackground(leftDrawable);
titleTextView.setText(titleText);
titleTextView.setGravity(Gravity.CENTER);//设置居中
//设置本layout的背景色
setBackgroundColor(Color.BLUE);
//设置内部view的位置属性
leftParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
titleParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
//设置内部view的对齐属性
leftParams.addRule(RelativeLayout.ALIGN_LEFT,TRUE);
//把内部view添加进布局中去,并将view和参数绑定
addView(leftButton,leftParams);
addView(titleTextView);
}
}