这是attrs.xml 文件需要定义的
<declare-styleable name="FanTopBar"> <attr name="fany_leftBackground" format="reference"/> <attr name="fany_rightBackground" format="reference"/> <attr name="fany_titleText" format="string"/> <attr name="fany_titleTextSize" format="dimension"/> <attr name="fany_titleTextColor" format="color"/> </declare-styleable>
这是类里面写 public class BiaotiLan extends RelativeLayout { private Button leftButton; private Button rigtButton; private TextView titleTextView; private TypedArray typedArray; public BiaotiLan(Context context) { super(context); } public BiaotiLan(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.biaoti,this); leftButton = findViewById(R.id.btn_fan); rigtButton = findViewById(R.id.btn_duo); titleTextView = findViewById(R.id.t1); //获得自定义属性并赋值 typedArray = context.obtainStyledAttributes(attrs, R.styleable.FanTopBar); int leftBtnBackground = typedArray.getResourceId(R.styleable.FanTopBar_fany_leftBackground, 0); int rightBtnBackgount = typedArray.getResourceId(R.styleable.FanTopBar_fany_rightBackground, 0); String titleText = typedArray.getString(R.styleable.FanTopBar_fany_titleText); float titleTextSize = typedArray.getDimension(R.styleable.FanTopBar_fany_titleTextSize, 0); int titleTextColor = typedArray.getColor(R.styleable.FanTopBar_fany_titleTextColor, 0x38ad5a); //释放资源 typedArray.recycle(); leftButton.setBackgroundResource(leftBtnBackground); rigtButton.setBackgroundResource(rightBtnBackgount); titleTextView.setText(titleText); titleTextView.setTextSize(titleTextSize); titleTextView.setTextColor(titleTextColor); } public BiaotiLan(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } }