Andorid制作内含控件的自定义布局

来源:互联网 发布:golang io.readfull 编辑:程序博客网 时间:2024/05/16 06:31

首先可以先写一个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();//实例化内部viewleftButton = 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);}}


0 0
原创粉丝点击