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

当前回答

添加一个Kotlin扩展

如果您要经常这样做,那么添加扩展可以使您的代码更具可读性。按钮扩展TextView;如果你想要更窄,使用按钮。

fun TextView.leftDrawable(@DrawableRes id: Int = 0) {
    this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}

要使用扩展,只需调用

view.leftDrawable(R.drawable.my_drawable)

任何时候你需要清除,不要传递一个参数或做另一个名为removeDrawables的扩展

其他回答

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

试试这个:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
     fillButton[i].setBackground(getBaseContext().getResources().getDrawable(R.drawable.drawable_name));
}
else {
    fillButton[i].setBackgroundColor(Color.argb(255,193,234,203));
}

如果你正在使用drawableStart, drawableEnd, drawableTop或drawableBottom;你必须使用“setCompoundDrawablesRelativeWithIntrinsicBounds”

edittext.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.anim_search_to_close, 0)

试试这个:

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

添加一个Kotlin扩展

如果您要经常这样做,那么添加扩展可以使您的代码更具可读性。按钮扩展TextView;如果你想要更窄,使用按钮。

fun TextView.leftDrawable(@DrawableRes id: Int = 0) {
    this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}

要使用扩展,只需调用

view.leftDrawable(R.drawable.my_drawable)

任何时候你需要清除,不要传递一个参数或做另一个名为removeDrawables的扩展