首页 > 解决方案 > onActivityResult中访问ViewHolder参数

问题描述

我有一个RecylerviewwithButtonTextViewas 参数。我在单击按钮时打开文件选择器。

@Override
public void onBindViewHolder(final FileChooserAdapter.MyViewHolder holder, final int position) {
    PojoClass pojoClass = pojoClassList_.get(position);
    holder.listViewName.setText(pojoClass.getListName());
    holder.fileBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent filePickIntent = new Intent(Intent.ACTION_GET_CONTENT);
            filePickIntent.setType("*/*");
            startActivityForResult(filePickIntent, 1);
        }
    });

}

现在,在选择文件后,我在OnActivityResult displayName变量中获取文件名。我想设置holder.textview.setText(displayName);in onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case 1:
        // Get the Uri of the selected file
        Uri uri = data.getData();
        String uriString = uri.toString();
        File myFile = new File(uriString);
        String path = myFile.getAbsolutePath();


        if (uriString.startsWith("content://")) {
            Cursor cursor = null;
            try {
                cursor = getContentResolver().query(uri, null, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                }
            } finally {
                cursor.close();
            }
        } else if (uriString.startsWith("file://")) {
            displayName = myFile.getName();
        }
        // I want to place the holder.textview.setText(displayName) here
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

帮帮我,如何将ViewHolder参数放在Adapter.

标签: androidandroid-recyclerviewonactivityresultrecyclerview-layout

解决方案


几条笔记

的参数应该只由类本身管理ViewHolderholderAdapter

你可以做什么

  • 保存从 接收到的当前选定文件的引用onActivityResult,或者使用本地存储,如 ( List, SharedPreferences,Realm等)

  • 使用列表中的最新文件项再次填充文件选择器适配器

  • 调用notifyDataSetChanged()

公共无效 notifyDataSetChanged ()

通知附加的观察者底层数据已更改,任何反映数据集的视图都应自行刷新。

阅读更多


推荐阅读