Android自定义简单TextView

自定义属性

<declare-styleable name="TextView">
        <!--
        name 属性名称
        format 格式:string 文字 color颜色
        dimension 宽高 字体大小 integer数字
        reference 资源引用(drawable)
        -->
        <attr name="YiRanText" format="string"/>
        <attr name="YiRanTextColor" format="color"/>
        <attr name="YiRanTextSize" format="dimension"/>
        <attr name="YiRanMaxLength" format="integer"/>
        <!--background是自定义View管理的,可以不用 -->
        <attr name="YiRanBackground" format="reference|color"/>
        <!--枚举-->
        <attr name="YiRanInputType">
            <enum name="number" value="1"/>
            <enum name="text" value="2"/>
            <enum name="password" value="3"/>
        </attr>
    </declare-styleable>

整体代码

public class TextView extends View {
   
   

    private String mText;
    private int mTextSize=15;
    private int mTextColor= Color.BLACK;
    private Paint mPaint;


    //这个构造函数会在代码里面new的时候调用
    //TextView tv=new TextView(this)
    public TextView(Context context) {
   
   
        this(context,null);
    }

    //在布局中使用
    /*
    <com.example.customview.customview.text.TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="11111"
     />
    * */
    public TextView(Context context, @Nullable AttributeSet attrs) {
   
   
        this(context, attrs,0);
    }


    //在布局layout中使用(调用),但是会有style
    public TextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
   
   
        super(context, attrs, defStyleAttr);
        //获取自定义属性
        TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.TextView);
        mText=array.getString(R.styleable.TextView_YiRanText);
        mTextColor=array.getColor(R.styleable.TextView_YiRanTextColor,mTextColor);
        mTextSize=array.getDimensionPixelSize(R.styleable.TextView_YiRanTextSize,spToPx(mTextSize));

        //回收
        array.recycle();
        mPaint=new Paint();
        //抗锯齿
        mPaint.setAntiAlias
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值