TypedArray中的getDrawable()返回null?

Kar*_*uri 9 android drawable custom-component attr

在我的TypedArray.getDrawable()一个自定义中,我遇到了一个奇怪的问题View.为简单起见,这是一个显示同样问题的简单测试项目:

TestView.java

package com.example.testing;

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

public class TestView extends View {

    private Drawable mDrawable;

    public TestView(Context context) {
        this(context, null);
    }

    public TestView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TestView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TestView, defStyle, 0);
        try {
            Drawable d = a.getDrawable(R.styleable.TestView_testDrawable);
            if (d != null) {
                setDrawable(d);
            }
        } finally {
            a.recycle();
        }
    }

    private void setDrawable(Drawable d) {
        mDrawable = d;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mDrawable != null) {
            mDrawable.draw(canvas);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

RES /值/ attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>    
    <declare-styleable name="TestView">
        <attr name="testDrawable" format="reference|color" />
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

RES /布局/ main_activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res/com.example.testing"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

     <com.example.testing.TestView
         android:id="@+id/testView1"
         android:layout_width="match_parent"
         android:layout_height="100dp"
         custom:testDrawable="#ff0099" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

我没有看到可爱的粉红色矩形(既不在布局编辑器中也不在实际设备上).我不明白什么是错的.

ank*_*.de 1

我检查了你的代码,mDrawable它不为空,但它的大小是-1 x -1。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    mDrawable.setBounds(0, 0, View.MeasureSpec.getSize(widthMeasureSpec), View.MeasureSpec.getSize(heightMeasureSpec));
}
Run Code Online (Sandbox Code Playgroud)

这对我有用。我不知道这是否是你想要的,但也许这是一个起点