本文翻译自:How to programmatically set drawableLeft on Android button?
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. 除了可绘制之外,我可以做任何事情。
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);
#1楼
参考:https://stackoom.com/question/ItKf/如何在Android按钮上以编程方式设置drawableLeft
#2楼
你也可以尝试一下
txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);
#3楼
对我来说,它有效:
button.setCompoundDrawablesWithIntrinsicBounds(com.example.project1.R.drawable.ic_launcher, 0, 0, 0);
#4楼
试试这个:
((Button)btn).getCompoundDrawables()[0].setAlpha(btn.isEnabled() ? 255 : 100);
#5楼
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);
#6楼
myEdtiText.setCompoundDrawablesWithIntrinsicBounds( R.drawable.smiley,0, 0, 0);