如何以编程方式更改按钮的图标?

时间:2010-11-22 22:37:09

标签: android layout text button icons

我已经有了按钮:

<Button 
android:layout_height="wrap_content" 
android:layout_width="fill_parent"
android:drawableLeft="@drawable/empty"
android:id="@+id/buttonMyText" 
android:text="  myText" 
android:textSize="20px" 
android:gravity="left">
</Button>

程序启动时按钮上显示“空”图标。

我想要做的是根据用户输入从我的代码(低,中和高)自动更改按钮的图标

我试过了:

Button myButton = bla... bla... bla...

但我无法弄清楚

myButton.(what?)

2 个答案:

答案 0 :(得分:41)

如果您查看文档,您将看到每个XML属性的等效代码。

见这里:http://developer.android.com/reference/android/widget/Button.html

搜索drawableLeft节目:

android:drawableLeft:
setCompoundDrawablesWithIntrinsicBounds(Drawable,Drawable,Drawable,Drawable)

答案 1 :(得分:7)

如果您想在按钮点击事件中更改图标,请尝试使用此代码...

buttonMyText.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
       buttonMyText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ImageNameHere, 0, 0, 0);
       buttonMyText.setTextColor(Color.BLACK);
    }
});