简体   繁体   English

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

[英]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. 从state1state2 ,反之亦然。

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) 心脏是2个不同的可绘制对象(@ drawable / ic_fav_dish_color和@ drawable / ic_fav_dish_grey),文本是2个不同的字符串(@ string / dish_faved和@ string / dish_not_faved)

I made the button in xml with that code: 我用该代码在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>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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