当前位置: 代码迷 >> Android >> 带有onClick的已加星标功能
  详细解决方案

带有onClick的已加星标功能

热度:74   发布时间:2023-08-04 12:35:35.0

您好,我的视图上有一个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();

                } 




        }
    });

先感谢您!

使用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="" />
  相关解决方案