未使用 RecyclerView.Adapter 中的 onActivityResult [英] onActivityResult inside a RecyclerView.Adapter not being used
问题描述
我在适配器中有一个按钮,可以进入图库:
I have a button inside an Adapter which goes into gallery:
MyAdapter extends
RecyclerView.Adapter<RecyclerView.ViewHolder> {
...
onClic..{
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
((Activity) context).startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);}
....
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
}
}
..
}
我想做的是用从图库中选择的图像更新 ImageView,但为了做到这一点,我必须使用 onActivityResult 并且编译器抱怨 方法 onActivityResult 从未使用
和 无法解析 onActivityResult 方法
.
What I'm trying to do is to update an ImageView with the image selected from the gallery, but in order to do that I have to use onActivityResult and the compiler is complaining method onActivityResult is never used
and cannot resolve method onActivityResult
.
我该怎么办?
推荐答案
注意在这一行你使用了一个 Activity
来调用 startActivityForResult
:
Note on this line you are using an Activity
to call startActivityForResult
:
((Activity) context).startActivityForResult();
onActivityResult(...)
是一个回调方法,应该在你用来调用 startActivityForResult()
的同一个 Activity
中.
onActivityResult(...)
is a callback method and should be in the same Activity
you used to call startActivityForResult()
.
您收到编译器错误,因为没有这样的方法可以覆盖 RecyclerView.Adapter
的名为 onActivityResult(...)
.
You are getting the compiler error because there is no such method to override named onActivityResult(...)
for RecyclerView.Adapter
.
既然你问如何正确地做到这一点,这里是一种选择.
Since you asked how you can do this properly here is one option.
在MyAdapter
中添加如下接口:
public interface OnClickImageListener{
void onClick();
}
然后让您的对话框实现该接口.在 onClick
方法中执行:
Then have your dialog implement that interface. In the onClick
method do:
@Override
public void onClick() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
您可以将 onActivityResult(...)
方法添加到您的 Fragment
中,现在它将被调用.
You can add the onActivityResult(...)
method to your Fragment
and it will now be called.
要在创建 MyAdapter
时使用它,将 Fragment
作为参数传递给构造函数并将其作为 OnClickImageListener
引用,以便单击适配器中的侦听器简单地变为:
To use this when you create MyAdapter
pass the Fragment
in as an argument to the constructor and reference it as a OnClickImageListener
so your click listener in the adapter simply becomes:
imageClickListener.onClick();
另请注意,您可以向 onClick()
方法或其他任何您需要知道适配器中的哪个项目在返回图像后填充图像的方法添加索引.
Also note you can add an index to the onClick()
method or whatever else you need to know which item in the adapter to populate the image with once it is returned.
这篇关于未使用 RecyclerView.Adapter 中的 onActivityResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!