You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:复刻谷歌翻译项目中从SharedPreferences移除收藏项

解决星标按钮点击时获取对应项索引并删除SharedPreferences数据的方案

方案1:给StarButton直接绑定索引参数

在列表项的Adapter(比如RecyclerView.Adapter)中,绑定点击事件时直接传入当前项的索引:

// 以RecyclerView的Adapter为例,在onBindViewHolder方法内
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    TranslationItem currentItem = translationList.get(position);
    holder.starButton.setChecked(currentItem.isStarred());
    
    holder.starButton.setOnClickListener(v -> {
        currentItem.setStarred(!currentItem.isStarred());
        if (!currentItem.isStarred()) {
            // 直接将索引传入删除方法
            removeFromSharedPreferences(position);
            // 更新列表
            translationList.remove(position);
            notifyItemRemoved(position);
        }
    });
}

方案2:用数据唯一标识替代索引

如果列表存在排序、新增等变动导致索引失效,给每条翻译数据生成唯一标识(比如UUID、输入+翻译文本的组合哈希),存储时用该标识作为key:

// 存储数据时
String uniqueId = UUID.randomUUID().toString();
SharedPreferences.Editor editor = getSharedPreferences("translations", MODE_PRIVATE).edit();
editor.putString(uniqueId + "_input", inputText);
editor.putString(uniqueId + "_result", translatedText);
editor.apply();

// 删除方法接收唯一标识
private void removeFromSharedPreferences(String uniqueId) {
    SharedPreferences.Editor editor = getSharedPreferences("translations", MODE_PRIVATE).edit();
    editor.remove(uniqueId + "_input");
    editor.remove(uniqueId + "_result");
    editor.apply();
}

在Adapter点击事件中,直接获取当前项的uniqueId传入删除方法即可。

方案3:通过Tag传递索引

给StarButton设置Tag存储索引,点击时从Tag中取出:

// 在onBindViewHolder中
holder.starButton.setTag(position);
holder.starButton.setOnClickListener(v -> {
    int targetPosition = (int) v.getTag();
    TranslationItem item = translationList.get(targetPosition);
    if (!item.isStarred()) {
        removeFromSharedPreferences(targetPosition);
        translationList.remove(targetPosition);
        notifyItemRemoved(targetPosition);
    }
});

内容的提问来源于stack exchange,提问作者Ulrik R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:40:43