如何在android中使用onclick更改按钮?

如何在android中使用onclick更改按钮?,android,xml,button,onclick,Android,Xml,Button,Onclick,我有一个按钮,当我从中单击按钮时,它的外观应该会改变 反之亦然 心形是两种不同的可拉丝(@drawable/ic_fav_dish_color&@drawable/ic_fav_dish_grey),文本是两种不同的字符串(@string/dish_faved&@string/dish_not faved) 我用xml制作了按钮,代码如下: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

我有一个按钮,当我从中单击按钮时,它的外观应该会改变
反之亦然

心形是两种不同的可拉丝(@drawable/ic_fav_dish_color&@drawable/ic_fav_dish_grey),文本是两种不同的字符串(@string/dish_faved&@string/dish_not faved)

我用xml制作了按钮,代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/fav_dish_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/ic_fav_dish_color"
        android:gravity="start|center_vertical"
        android:text="@string/dish_faved"
        android:textAlignment="center"
        android:layout_margin="8dp"/>
</LinearLayout>

您应该在按钮上创建一个单击侦听器,如下所示:

Button mButton=(Button)findViewById(R.id.fav_dish_button);

mButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
       mButton.setText(getResources().getString(R.string.dish_not_faved);); 
       mButton.setBackgroundResource(R.drawable.ic_fav_dish_grey);
    } 
});
更新:

如果要更改可绘制左侧,请尝试以下代码:

        // Left, top, right, bottom drawables
Drawable[] drawables = mButton.getCompoundDrawables();
        // get left drawable.
Drawable leftCompoundDrawable = drawables[0];
        // get desired drawable.
Drawable img = getContext().getResources().getDrawable(R.drawable.ic_fav_dish_grey);
        // set image size (don't change the size values)
img.setBounds(leftCompoundDrawable.getBounds());
        // set new drawable
mButton.setCompoundDrawables(img, null, null, null);

你可以使用这个,你应该有两个图像,一个是填充,另一个是 不是


如果我这样做,图标将显示为按钮的整个背景,而不是仅显示在左侧。如果我再次单击,如何实现反之亦然?您可以创建一个变量作为标志来保持状态。
final Button btn = (Button)(findViewById(R.id.fav_dish_button));
final Drawable drawable = getResources().getDrawable(R.drawable.your_fill_heart_image_name);
btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            btn.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);

        }
    });