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

当前回答

试试这个:

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

其他回答

对我来说,它起作用了:

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

芬兰湾的科特林版本

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

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

}

为我工作。设置可绘制在右边

tvBioLive.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close_red_400_24dp, 0)

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

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