我在动态创建按钮。我首先使用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>

这是我目前得到的。我什么都能做,就是画不出来。

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);

当前回答

芬兰湾的科特林版本

使用下面的代码片段添加一个可绘制的左侧按钮:

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

使用Android Vector Drawable的要点

当你使用android vector drawable并且想要向后兼容低于21的API时,添加以下代码:

在应用程序级别build.gradle:

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

应用类:

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    }

}

其他回答

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

 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);
}

简单地说,你也可以试试这个

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

试试这个:

((Button)btn).getCompoundDrawables()[0].setAlpha(btn.isEnabled() ? 255 : 100);
myEdtiText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

你可以使用setCompoundDrawables方法来做到这一点。请看这里的例子。我使用这个没有使用setBounds,它工作。两种方法你都可以试试。

更新:复制代码在这里,以防链接下降

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);