在列表视图中添加收藏按钮

Posted

技术标签:

【中文标题】在列表视图中添加收藏按钮【英文标题】:Adding favorite button in list view 【发布时间】:2016-03-31 22:07:00 【问题描述】:

我有一个listview,它对每个列表项都有一个收藏按钮,单击该按钮应将该列表项添加到另一个名为 my fav9rites 的活动中。我将Baseadapter 用于listviewSharedpreference 用于添加收藏夹。 当我单击收藏按钮时,列表视图项目被添加到我的收藏活动中,但我面临以下问题:

1) 收藏按钮在点击时会变暗,表示列表项已添加到收藏夹。发生这种情况,但是当我关闭活动并再次返回时,按钮会恢复而不是变暗

2)在我的收藏夹活动中长按列表项,列表项应该从收藏夹中删除,但这不会发生。

希望大家理解我的问题

我的代码

我的基本适配器

public View getView(final int position, View view, ViewGroup parent)

    final ViewHolder holder;
    if(view == null)
        holder = new ViewHolder();
        view = inflater.inflate(R.layout.beg_list_item,null);
        holder.listHeading = (TextView) view.findViewById(R.id.beg_list_itemTextView);
    //  holder.listHash = (TextView) view.findViewById(R.id.listview_hashtags);
        holder.alphabetList = (ImageView) view.findViewById(R.id.beg_list_itemImageView);
        holder.favoriteImg = (ImageView) view.findViewById(R.id.favbtn);
        view.setTag(holder);

    else
        holder = (ViewHolder) view.getTag();
        
        CodeList code = (CodeList) getItem(position);
        holder.listHeading.setText(codeList.get(position).getListHeading());
        imageLoader.DisplayImage(codeList.get(position).getAlphabetimg(),
                                holder.alphabetList);
    //  holder.listHash.setText(codeList.get(position).getListHashTags());                      

    if (checkFavoriteItem(code)) 
        holder.favoriteImg.setImageResource(R.drawable.favorite);
        holder.favoriteImg.setTag("yes");
     else 
        holder.favoriteImg.setImageResource(R.drawable.unfavorite);
        holder.favoriteImg.setTag("no");
    

            view.setOnClickListener(new OnClickListener()

                @Override
                public void onClick(View arg0)
                    Intent intent = new Intent(context, SingleItemView.class);

                    //intent.putExtra("listheading",
                    //       (codeList.get(position).getListHeading()));
                    //intent.putExtra("alphabetimg",
                    //              (codeList.get(position).getAlphabetimg()));

                    intent.putExtra("demovideo",
                                    (codeList.get(position).getDailogdemovideo()));

                    intent.putExtra("download",
                                    (codeList.get(position).getDownloadCode()));

                    // Start SingleItemView Class
                    context.startActivity(intent);

                
            );



            final ImageView favoritesbutton = (ImageView) view.findViewById(R.id.favbtn);

            favoritesbutton.setOnClickListener(new OnClickListener()

                @Override
                public void onClick(View v)
                    String tag = favoritesbutton.getTag().toString();

                    if(tag.equalsIgnoreCase("no"))
                        shrdPrefence.addFavorite(context, codeList.get(position));

                        Toast.makeText(context, R.string.fav_added, Toast.LENGTH_SHORT).show();

                        favoritesbutton.setTag("yes");
                        favoritesbutton.setImageResource(R.drawable.favorite);
                    else
                        shrdPrefence.removeFavorite(context, codeList.get(position));
                        favoritesbutton.setTag("no");
                        favoritesbutton.setImageResource(R.drawable.unfavorite);
                        Toast.makeText(context, R.string.fav_removed, Toast.LENGTH_SHORT).show();
                    
                
            );


    return view;


//Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(CodeList checkCode) 
    boolean check = false;
    List<CodeList> favorites = shrdPrefence.getFavorites(context);
    if (favorites != null) 
        for (CodeList code : favorites) 
            if (code.equals(checkCode)) 
                check = true;
                break;
            
        
    
    return check;



public void add(CodeList code) 

    codeList.add(code);
    notifyDataSetChanged();



public void remove(CodeList code) 

    codeList.remove(code);
    notifyDataSetChanged();

sharedpreference.java

public class SharedPreference


public static final String PREFS_NAME = "MY_APP";
public static final String FAVORITES = "code_Favorite";

public SharedPreference()
    super();


public void saveFavorites(Context context, List<CodeList> favorites)
    SharedPreferences settings;
    Editor editor;

    settings = context.getSharedPreferences(PREFS_NAME,
                                            Context.MODE_PRIVATE);
    editor = settings.edit();

    Gson gson = new Gson();
    String jsonFavorites = gson.toJson(favorites);

    editor.putString(FAVORITES, jsonFavorites);

    editor.commit();


public void addFavorite(Context context, CodeList code)
    List<CodeList> favorites = getFavorites(context);

    if(favorites == null)
        favorites = new ArrayList<CodeList>();
        favorites.add(code);
        saveFavorites(context,favorites);


public void removeFavorite(Context context, CodeList code) 
    ArrayList<CodeList> favorites = getFavorites(context);
    if (favorites != null) 
        favorites.remove(code);
        saveFavorites(context, favorites);
        
    


public ArrayList<CodeList> getFavorites(Context context) 
    SharedPreferences settings;
    List<CodeList> favorites;

    settings = context.getSharedPreferences(PREFS_NAME,
                                            Context.MODE_PRIVATE);

    if (settings.contains(FAVORITES)) 
        String jsonFavorites = settings.getString(FAVORITES, null);
        Gson gson = new Gson();
        CodeList[] favoriteItems = gson.fromJson(jsonFavorites,
                                                CodeList[].class);

        favorites = Arrays.asList(favoriteItems);
        favorites = new ArrayList<CodeList>(favorites);
     else
        return null;

    return (ArrayList<CodeList>) favorites;



我最喜欢的..java

    public class MyFavActivity extends Activity
    
    SharedPreference shrdPrfence;
    List<CodeList> favorites;

    FinalAdapter fnlAdpter;
    Context context = this.context;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fav_layout);

        shrdPrfence = new SharedPreference();
        favorites = shrdPrfence.getFavorites(MyFavActivity.this);

        if(favorites == null)
            Dialog dialog = new Dialog(MyFavActivity.this);
            dialog.setTitle(R.string.nofav_title);
            dialog.show();
        else
            if(favorites.size() == 0)
                Dialog dialog = new Dialog(MyFavActivity.this);
                dialog.setTitle(R.string.nofav_title);
                dialog.show();
            

            ListView favList = (ListView) findViewById(R.id.fav_layoutListView);

            if(favorites != null)
                fnlAdpter = new FinalAdapter(MyFavActivity.this, favorites);
                favList.setAdapter(fnlAdpter);

                favList.setOnItemClickListener(new OnItemClickListener() 

                        public void onItemClick(AdapterView<?> parent, View arg1,
                                                int position, long arg3) 

                        
                    );





                favList.setOnItemLongClickListener(new OnItemLongClickListener() 

                        @Override
                        public boolean onItemLongClick(AdapterView<?> parent, View view,
                            int position, long id) 

                            ImageView button = (ImageView) view
                                .findViewById(R.id.favbtn);

                            String tag = button.getTag().toString();
                            if (tag.equalsIgnoreCase("no")) 
                                shrdPrfence.addFavorite(MyFavActivity.this,
                                                             favorites.get(position));
                                Toast.makeText(
                                    MyFavActivity.this,
                                        R.string.fav_added,
                                    Toast.LENGTH_SHORT).show();

                                button.setTag("yes");
                                button.setImageResource(R.drawable.favorite);
                             else 
                                shrdPrfence.removeFavorite(MyFavActivity.this,
                                                                favorites.get(position));
                                button.setTag("no");
                                button.setImageResource(R.drawable.unfavorite);
                                fnlAdpter.remove(favorites.get(position));
                                Toast.makeText(
                                    MyFavActivity.this,
                                        R.string.fav_removed,
                                    Toast.LENGTH_SHORT).show();
                            
                            return true;
                        
                    );
            
        
        

   

【问题讨论】:

您检查过code.equals(checkCode) 是否有效吗?你实现了.equals 方法了吗? @Roshan 是的,检查过。它有效 【参考方案1】:

实际上您的 saveFavorites() 方法工作正常,因为您只需调用 gson.toJson() (将所有内容转换为 json 格式)

您想使用 SharedPreferences 获取保存的数据,并且您已使用此行检索数据

 gson.fromJson(jsonFavorites, CodeList[].class);

你永远不会用这一行得到你保存的数据,因为你保存了一个 list 并且你想检索一个 array (!)

如果您保存了列表,则必须使用列表令牌检索数据。你需要这条线

 gson.fromJson(jsonFavorites,new TypeToken<ArrayList<CodeList>>() .getType());

我认为这将解决您的问题。祝你好运。

【讨论】:

感谢您的帮助。正如你所说的那样尝试了,但是当我打开我的收藏夹活动时,应用程序崩溃了,我在 logcat 中得到了这个。无法启动活动 ComponentInfocom.enlightenme.pac/com.enlightenme.pac.MyFavActivity:java.lang.ClassCastException:java.util.ArrayList 无法转换为 com.enlightenme.pac.CodeList[]

以上是关于在列表视图中添加收藏按钮的主要内容,如果未能解决你的问题,请参考以下文章

单击收藏夹按钮时更新列表视图

如何从列表视图按钮单击将多个数据添加到数组列表?

检索数据表单数据库后列表视图不更新

在主屏幕小部件的列表视图上方添加一个按钮 - 如何捕获单击此按钮?

单击按钮将项目添加到另一个视图控制器表视图

在垂直列表视图中添加水平列表视图时不正确使用 ParentDataWidget