如何在Android按钮上以编程方式设置drawableLeft? [英] How to programmatically set drawableLeft on Android button?
本文介绍了如何在Android按钮上以编程方式设置drawableLeft?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在动态创建按钮。我首先使用XML来设置它们,我正在尝试使用下面的XML并使其成为编程。
I'm dynamically creating buttons. I styled them using XML first, and I'm trying to take the XML below and make it programattic.
<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>
这是我到目前为止所拥有的。除了drawable之外,我可以做任何事情。
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);
推荐答案
您可以使用 setCompoundDrawables
执行此操作的方法。请参阅示例此处。我在没有使用 setBounds
的情况下使用了它,并且它有效。您可以尝试任何一种方式。
You can use the setCompoundDrawables
method to do this. See the example here. I used this without using the setBounds
and it worked. You can try either way.
更新:在此处复制代码,导致链接失效
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 );
或
Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );
txtVw.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null);
或
txtVw.setCompoundDrawablesWithIntrinsicBounds( R.drawable.smiley, 0, 0, 0);
这篇关于如何在Android按钮上以编程方式设置drawableLeft?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文