當前位置:首頁 > IT技術 > 移動平臺 > 正文

android之自定義屬性--獲屬性值--并繪制
2021-09-16 11:45:58

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));
        }
        //第三種:使用系統(tǒng)工具,獲取屬性
        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);
    }
}

?

本文摘自 :https://blog.51cto.com/u

開通會員,享受整站包年服務立即開通 >