当我点击按钮时,我有这个按钮应该改变它的外观 state1至state2,反之亦然。
心脏是2个不同的drawables(@ 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>
答案 0 :(得分: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);
}
});
答案 1 :(得分: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);