繁体   English   中英

单击按钮更改回收站视图中的数据

[英]change data in recycler view with click of button

因此,我正在尝试创建一个挑战游戏,您可以从中选择 2 个选项,我在回收站视图设置中有 2 个卡片视图设置,我将如何更改其中的值以通过单击按钮获得新的挑战如果用户想要一个新的挑战,从主要活动? 我使用 SQLite 数据库随机从每场战斗中获取数据。

我的 onBindViewHolder

@Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        SQLiteDatabase sqLiteDatabase = faceMashDatabaseHelper.getReadableDatabase();
        cursor = sqLiteDatabase.query("images", new String[]{"id","filename","name"},null,null,null,null,null);
        MyViewHolder myViewHolder = (MyViewHolder) holder;
        int position1 = (int)(Math.random()*(faceMashDatabaseHelper.getCount()-0+1)+0);
        cursor.moveToPosition(position1);
        String filename = cursor.getString(cursor.getColumnIndex("filename"));
        String name = cursor.getString(cursor.getColumnIndex("name"));
        CardView cardView = myViewHolder.getCardView();
        ImageView imageView = (ImageView) cardView.findViewById(R.id.imageView);
        TextView nameView = (TextView) cardView.findViewById(R.id.nameView);
        nameView.setText(name);
        File file = context.getFileStreamPath(filename);
        if(file.exists()){
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            imageView.setImageBitmap(bitmap);

        }
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = nameView.getText().toString();
                listener.onClick(position,name);
            }
        }); //This on click is for the card views themselves.



    }

我的 onClick 目前正在使用工具栏选项

case R.id.newbattle:
faceMashAdapter.notifyDataSetChanged();

首先,您永远不应该在onBindViewHolder中做繁重的工作,因为每次在回收后重新创建您的视图时都会调用它(因为它未被使用)。

您应该在适配器之外查询您的数据库,并使用您查询的数据占用一个列表。 您的 List 应该有与RecyclerView的条目一样多的条目。 然后,您可以使用onBindViewHolder中的position参数来始终获取条目的正确数据( list.get(position) )。

这样,您只需更改 List 的内容并通过notifyItemChanged通知 Adapter 哪些项目已更改(或者如果所有项目都应刷新,请使用notifyDataSetChanged )。 这样适配器的内容就会被刷新。

所以你应该在你的onClick中做的是更新你的列表的内容并通知适配器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM