2017-07-21 59 views
1

我有這個按鈕,當我點擊從
state1state2,反之亦然時,它應該改變它的外觀。如何在android中使用onclick更改按鈕?

的心臟是2個不同的可繪製(@繪製/ ic_fav_dish_color & @繪製/ ic_fav_dish_grey)和文字是兩種不同的字符串(@字符串/ dish_faved & @字符串/ 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> 

回答

2

你可以使用這個,你應該有兩個圖像一個是補等是 不

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

     } 
    }); 
0

你應該做一個點擊監聽這個按鈕,如下圖所示:

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

如果我這樣做,該圖標將顯示爲按鈕的整個背景,而不是僅在左側 –

+0

@ M.Mungenast我已經更新了我的答案。 – huk

+0

以及如果我再次點擊,我如何實現反之亦然? –

相關問題