簡體   English   中英

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

[英]How do I change a button with onclick in android?

我有這個按鈕,當我從
從state1state2 ,反之亦然。

心臟是2個不同的可繪制對象(@ drawable / ic_fav_dish_color和@ drawable / ic_fav_dish_grey),文本是2個不同的字符串(@ 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>

您可以使用它,您應該有兩個圖像,一個是填充圖像,另一個不是

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

        }
    });

您應該在按鈕上創建一個點擊監聽器,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM