简体   繁体   中英

How do I change a button with onclick in android?

I have this button that should change its appearance when I click the button from
state1 to state2 and vice versa.

the heart is 2 different drawables (@drawable/ic_fav_dish_color & @drawable/ic_fav_dish_grey) and the text is 2 different strings (@string/dish_faved & @string/dish_not_faved)

I made the button in xml with that code:

<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>

you can use this , you should have two images one that is fill and other is not

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);

        }
    });

You should make a click listener on your button like below:

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);
    } 
});

Update:

Try below code if you want to change drawable left:

        // 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM