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

首先可以先写一个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);
		
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值