4

Я пытаюсь подгрузить Drawable из ресурса. В папке values лежит файл atts.xml, который содержит

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomView">
        <attr name="keyBackground" format="reference"/>
    </declare-styleable>
</resources>

В папке laoyout лежит файл custom_input.xml

<com.example.android.softkeyboard.CustomView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/customView"
        keyBackground="@drawable/key_background"
        />

В папках drawable-xxx лежит изображение key_background.png. Когда View создается, снаружи вызывается код

@Override public View onCreateInputView() {
    mInputView = (CustomView) getLayoutInflater().inflate(R.layout.custom_input, null);

    // ...

    return mInputView;
}

А внутри самого View:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);

LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Drawable mKeyBackground = a.getDrawable(R.styleable.CustomView_keyBackground);

И вот здесь проблема: mKeyBackground - null. Почему так и как это исправить?

1 ответ 1

0

у TypedArray getDrawable должен браться по индексу атрибута. По id ресурса Drawable берется у Resources.

http://developer.android.com/reference/android/content/res/TypedArray.html#getDrawable(int) http://developer.android.com/reference/android/content/res/Resources.html#getDrawable(int)

2
  • т.е. у вас должно быть Drawable mKeyBackground = context.getResources().getDrawable(R.styleable.CustomView_keyBackground);
    – kENNAAAAA
    9 фев 2012 в 15:59
  • Спасибо. Сделал так: Drawable mKeyBackground = getResources().getDrawable(R.drawable.key_background); 9 фев 2012 в 16:29

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.