Java 如何以编程方式在 Android 按钮上设置 drawableLeft?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4502605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 18:06:34  来源:igfitidea点击:

How to programmatically set drawableLeft on Android button?

javaandroidandroid-layoutandroid-2.2-froyo

提问by

I'm dynamically creating buttons. I styled them using XML first, and I'm trying to take the XML below and make it programattic.

我正在动态创建按钮。我首先使用 XML 对它们进行样式设置,然后尝试采用下面的 XML 并使其编程。

<Button
    android:id="@+id/buttonIdDoesntMatter"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:text="buttonName"
    android:drawableLeft="@drawable/imageWillChange"
    android:onClick="listener"
    android:layout_width="fill_parent">
</Button>

This is what I have so far. I can do everything but the drawable.

这就是我到目前为止所拥有的。除了drawable,我什么都能做。

linear = (LinearLayout) findViewById(R.id.LinearView);
Button button = new Button(this);
button.setText("Button");
button.setOnClickListener(listener);
button.setLayoutParams(
    new LayoutParams(
        android.view.ViewGroup.LayoutParams.FILL_PARENT,         
        android.view.ViewGroup.LayoutParams.WRAP_CONTENT
    )
);      

linear.addView(button);

采纳答案by Varun

You can use the setCompoundDrawablesmethod to do this. See the example here. I used this without using the setBoundsand it worked. You can try either way.

您可以使用该setCompoundDrawables方法来执行此操作。请参阅此处的示例。我在没有使用的情况下使用了setBounds它并且它起作用了。你可以尝试任何一种方式。

UPDATE: Copying the code here incase the link goes down

更新:在此处复制代码以防链接断开

Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
img.setBounds(0, 0, 60, 60);
txtVw.setCompoundDrawables(img, null, null, null);

or

或者

Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
txtVw.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null);

or

或者

txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

回答by Jignesh Ansodariya

Simply you can try this also

你也可以试试这个

txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

回答by swapnil saha

For me, it worked:

对我来说,它有效:

button.setCompoundDrawablesWithIntrinsicBounds(com.example.project1.R.drawable.ic_launcher, 0, 0, 0);

回答by user2969017

Try this:

尝试这个:

((Button)btn).getCompoundDrawables()[0].setAlpha(btn.isEnabled() ? 255 : 100);

回答by user1564762

I did this:

我这样做了:

 // Left, top, right, bottom drawables.
            Drawable[] drawables = button.getCompoundDrawables();
            // get left drawable.
            Drawable leftCompoundDrawable = drawables[0];
            // get new drawable.
            Drawable img = getContext().getResources().getDrawable(R.drawable.ic_launcher);
            // set image size (don't change the size values)
            img.setBounds(leftCompoundDrawable.getBounds());
            // set new drawable
            button.setCompoundDrawables(img, null, null, null);

回答by gnganpath

myEdtiText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

回答by ??? ???? ????

as @Jérémy Reynaud pointing out, as described in this answer, the safest way to set the left drawable without changing the values of the other drawables (top, right, and bottom) is by using the previous values from the button with setCompoundDrawablesWithIntrinsicBounds:

正如@Jérémy Reynaud 指出的,如本答案所述,在不更改其他可绘制对象(顶部、右侧和底部)的值的情况下设置左侧可绘制对象的最安全方法是使用带有setCompoundDrawablesWithIntrinsicBounds的按钮中的先前值:

Drawable leftDrawable = getContext().getResources()
                          .getDrawable(R.drawable.yourdrawable);

// Or use ContextCompat
// Drawable leftDrawable = ContextCompat.getDrawable(getContext(),
//                                        R.drawable.yourdrawable);

Drawable[] drawables = button.getCompoundDrawables();
button.setCompoundDrawablesWithIntrinsicBounds(leftDrawable,drawables[1],
                                               drawables[2], drawables[3]);

So all your previous drawable will be preserved.

因此,您之前的所有可绘制对象都将被保留。

回答by Muhaiminur Rahman

Might be helpful:

可能有帮助:

TextView location;
location=(TextView)view.findViewById(R.id.complain_location);
//in parameter (left,top,right,bottom) any where you wnat to put
location.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.arrow,0);

回答by aminography

? Kotlin Version

? Kotlin Version

Use below snippet to add a drawable left to the button:

使用以下代码段向按钮左侧添加可绘制对象:

val drawable = ContextCompat.getDrawable(context, R.drawable.ic_favorite_white_16dp)
button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)

.

.

? Important Point in Using Android Vector Drawable

? Important Point in Using Android Vector Drawable

When you are using an android vector drawableand want to have backward compatibility for API below 21, add the following codes to:

当您使用android vector drawable并希望对低于 21 的 API具有向后兼容性时,请将以下代码添加到:

In app level build.gradle:

在应用层面build.gradle

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

In Application class:

在应用程序类中:

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    }

}

回答by Rajneesh Shukla

Following is the way to change the color of the left icon in edit text and set it in left side.

以下是更改编辑文本中左侧图标颜色并将其设置在左侧的方法。

 Drawable img = getResources().getDrawable( R.drawable.user );
img.setBounds( 0, 0, 60, 60 );
mNameEditText.setCompoundDrawables(img,null, null, null);

int color = ContextCompat.getColor(this, R.color.blackColor);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    DrawableCompat.setTint(img, color);

} else {
    img.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}