问题描述
您好,我的视图上有一个imageView。 在我的活动中,我在onCreate ArrayList中创建,如果单击imageView,将在其中添加名称。 因此,如果列表包含此名称,则将从可绘制文件夹中加载填充的星形图像。 这是我的问题:如何写您单击imageView并加载另一个图像? 因此,如果有实心星,则应加载空星。
final ImageView img = (ImageView) rootView.findViewById(R.id.imageView1);
if (starredList.contains(txt1[p])){
img.setImageResource(R.drawable.ic_action_important);
}
else{
img.setImageResource(R.drawable.ic_action_not_important);
}
img.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View view)
{
Object tag = img.getTag();
int id = tag == null ? -1 :(Integer) tag;
if (id==R.drawable.ic_action_important){
img.setImageResource(R.drawable.ic_action_not_important);
}
if (id==R.drawable.ic_action_not_important){
img.setImageResource(R.drawable.ic_action_important);
starredList.add(txt1[p]);
Toast.makeText(getActivity(), txt1[p]+" wurde ihren Favoriten hinzugefügt", Toast.LENGTH_LONG).show();
}
}
});
先感谢您!
1楼
使用ToggleButton
并通过selector
处理那些drawable
。
在drawable
文件favorite_button_image.xml
中使用名为favorite_button_image.xml
selector
创建一个XML drawable,并将您的drawable作为以下XML中的item
添加...
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_action_important"
android:state_checked="true"/>
<item android:drawable="@drawable/ic_action_not_important"
android:state_checked="false"/>
</selector>
如下所示,将此ToggleButton
中的favorite_button_image
ToggleButton
设置为可绘制对象,并将此ToggleButton
添加到Layout XML
而不是ImageView
。
您将获得想要做的。
<ToggleButton
android:id="@+id/star"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="@drawable/favorite_button_image"
android:textOff=""
android:textOn="" />