由于某些未知原因,我无法向 RecyclerView 添加元素。
我有一个方法onActivityResult,我在其中做了以下事情:
file.add(new FileModel());
反过来,在 OnStart 方法中更高的地方:
file = new ArrayList<>();
fAdapter = new ADDFileAdapter(file);
rvAddFile.setAdapter(fAdapter);
如果我填写file该方法OnStart,则会添加并显示元素。
rvAddFile.setAdapter(fAdapter);
file.add(new FileModel());
file.add(new FileModel());
file.add(new FileModel());
问题是为什么在onActivityResult方法中没有将元素添加到RecyclerView中?
更新程序
public class ADDFileAdapter extends RecyclerView.Adapter<ADDFileAdapter.ADDFileViewHolder> {
ArrayList<FileModel> fileConteiner;
public ADDFileAdapter(ArrayList<FileModel> fileConteiner) {
this.fileConteiner = fileConteiner;
}
@Override
public ADDFileViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.add_file_card_layout, parent, false);
ADDFileAdapter.ADDFileViewHolder nh = new ADDFileAdapter.ADDFileViewHolder(v);
return nh;
}
@Override
public void onBindViewHolder(ADDFileViewHolder holder, int position) {
Context ctx = holder.itemView.getContext();
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams lparamsFile = new LinearLayout.LayoutParams(100,100);
LinearLayout linearLayoutFileContent = new LinearLayout(ctx); //Контейнер для вложения
linearLayoutFileContent.setLayoutParams(lparams);
for (int i = 0; i < fileConteiner.size(); i++){
ImageView file = new ImageView(ctx); //Изображение вложения
file.setLayoutParams(lparamsFile);
file.setImageDrawable(ctx.getResources().getDrawable(R.drawable.audio));
linearLayoutFileContent.addView(file);
}
holder.cv.addView(linearLayoutFileContent);
}
@Override
public int getItemCount() {
return fileConteiner.size();
}
public static class ADDFileViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
CardView cv;
public ADDFileViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.add_file_card);
}
@Override
public void onClick(View view) {
}
}
方法onActivityResult
if(u.toString().equals("image/jpeg")
|| u.toString().equals("image/png")
|| u.toString().equals("image/gif")
|| u.toString().equals("image/tiff")){
fileAdd.add(new FileModel());
fAdapter.notifyDataSetChanged();
}
调试器

在
onActivityResult()添加数据后:通过调用通知适配器更改
notifyDataSetChanged():如果这不起作用,则:
更新:
文件!=文件添加
那些。见上文第 2 点
将数据初始化移动到
onCreate. 显然,当它被调用时onActivityResult,片段的链接丢失了,虽然它并没有完全销毁,但传递到了舞台上onStop启动时
创建时
实际上OnActivityResult本身