getCompoundDrawables在onCreateView中返回null,但不是稍后

问题描述 投票:4回答:6

我想运行下面的代码,以便在pre-lollipop设备上为一个按钮的drawable着色,但是当在Fragment的onCreateView方法内部调用时,button.getCompoundDrawables()为数组的所有4个元素返回null。

如果我稍后检查相同的Drawable []数组 - 例如按钮单击事件 - 我可以看到已正确分配可绘制值(3为空,1有效)。

是否有一些按钮生命周期或片段生命周期,我可以依赖复合drawables数组已经正确初始化?

Drawable[] drawables = button.getCompoundDrawables();
        if( drawables[2] != null){
            Drawable wrapDrawable = DrawableCompat.wrap(drawables[2]);
            DrawableCompat.setTint(wrapDrawable, color);
            button.invalidate();
        }

这是我正在使用的lib版本:

compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:support-v4:24.1.1'
compile 'com.android.support:design:24.2.0'

根据要求,我还包括一些xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout        xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
 [...]  >

<Button
    android:id="@+id/bt1"
    android:background="@android:color/transparent"
    android:textAppearance="@style/ConfigButtonTheme"
    android:text="Sincronizar Música"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:drawableEnd="@drawable/ic_chevron_right_white_24dp"
    android:textAlignment="textStart"
    android:layout_width="match_parent"
    android:layout_height="60dp" />

</LinearLayout>
android
6个回答
22
投票

android:drawableEnd改为android:drawableRight。不知道为什么但是drawableEnd在onCreate()方法中返回null并且drawableRight工作正常。


21
投票

对于android:drawableRight,你应该使用getCompoundDrawables(),在android:drawableEnd,你应该使用getCompoundDrawablesRelative()

getCompouundDrawablesRelative()


0
投票

我的猜测是,尚未创建/膨胀drawable。尝试将该代码放入片段中的onActivityCreatedonStartonResume中。这些是按照在生命周期内调用它们的顺序,理想情况下,您希望尽快执行此操作。


0
投票

您可以以编程方式配置drawable,然后将其设置为文本视图。

 val textDrawable = resources.getDrawable(R.drawable.ic_arrow_upward_24dp, null)
 val color = ResourcesCompat.getColor(resources, R.color.colorAccent, null)
     textDrawable.setTint(color)

            //setCompoundDrawablesRelativeWithIntrinsicBounds(left, top, right, bottom)
     textView.setCompoundDrawablesRelativeWithIntrinsicBounds(null, textDrawable, null, null)

0
投票

android:drawableEnd改为android:drawableRight。不知道为什么但是drawableEndnull方法中返回onCreate()并且drawableRight工作正常。

要么

另一种方法是不将android:drawableEnd改为android:drawableRight。它将100%工作

只需编写如下代码:

onCreate(){
    //your all statement
    //at the end
    findViewById(android.R.id.content).post(new Runnable() {
   @Override
   public void run() {
     //write your code here you will get all the drawables
   }
   });
}

0
投票

它不会在开始时在TextView中加载drawable。你应该用

TextView.post({ 
    // get your drawables here.
})

这个函数可以在你加载时得到你的drawable。

© www.soinside.com 2019 - 2024. All rights reserved.