android之自定义属性--获属性值--并绘制

android之自定义属性--获属性值--并绘制

package com.example.test17;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class MyAttributeView extends View {

    private int myAge;
    private String myName;
    private Bitmap myBg;

    public MyAttributeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //获取属性三种方式
        //第一种:通过命名空间
        //在(.xml)文件中
        //Android studio: xmlns:yiqi="http://schemas.android.com/apk/res-auto"
        //eclipse: xmlns:yiqi="http://schemas.android.com/apk/<包名>"
        String age = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "my_age");
        String name = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "my_name");
        String bg = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "my_bg");

        //第二种:遍历属性集合
        for (int i = 0; i < attrs.getAttributeCount(); i++) {
//            System.out.println(attrs.getAttributeName(i) + "==" +attrs.getAttributeValue(i));
        }
        //第三种:使用系统工具,获取属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyAttributeView);
        for (int i = 0; i < typedArray.getIndexCount(); i++) {
            int index = typedArray.getIndex(i);
            switch(index){
                case R.styleable.MyAttributeView_my_age:
                {
                    myAge = typedArray.getInt(index,0);
                }
                    break;
                case R.styleable.MyAttributeView_my_name:
                    myName = typedArray.getString(index);
                    break;
                case R.styleable.MyAttributeView_my_bg:
                    BitmapDrawable drawable =(BitmapDrawable) typedArray.getDrawable(index);
                    myBg = drawable.getBitmap();
                    break;
            }
        }
        //记得回收
        typedArray.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        canvas.drawText(myName+"---"+myAge,50,50,paint);
        canvas.drawBitmap(myBg,50,50,paint);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

super码王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值