java - Activity 到 Fragment 发送数据并访问 Fragment 中的 arraylist
问题描述
我有一个fragment
存在于底部导航活动中。Fragments
包含自定义recyclerview
。当我按下一个评论按钮时,它会打开另一个评论活动。下面是在RecyclerView
适配器中。
viewholder.commentlay.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//commenttofragment.clear();
Intent comment = new Intent(fp, com.fooddoof.fuddict.comment.class);
int id = dusers.get(position).getId();
int comcount = dusers.get(viewholder.getAdapterPosition()).getCommentcount();
comment.putExtra("id",id);
comment.putExtra("ownerid",userid);
comment.putExtra("maincommentposition",position);
comment.putExtra("commentcountonposition", comcount);
fp.startActivityForResult(comment,1);
}
});
在完成一些任务后的评论活动中,我需要向 this 发送一些值fragment
。所以我重写了这个OnBackPressed
方法。我已经创建了一个方法Fragment
来接收它。
@Override
public void onBackPressed()
{
Bundle args = new Bundle();
args.putInt("maincommentcount",maincommentcount);
args.putInt("maincommentposition", maincommentposition);
FolowersPost f = new FolowersPost();
f.getdatafromcomment(args);
finish();
}
我在下面收到它Fragment
。
public void getdatafromcomment(Bundle args)
{
int count = args.getInt("maincommentcount");
int p=args.getInt("maincommentposition",999999999);
Log.e("Shiva","count--->"+count+"p--->"+p);
}
已收到值,但我需要访问传入的arraylist
值以显示. 但是当我回到. 我尝试访问它,但只能工作一段时间。我也将其声明为全局变量。Fragement
Adapter
recyclerView
fragment
OnCreateView
OnResume
Arraylist
解决方案
你现在已经在使用startActivityForResult.
你只需要使用onActivityResult.
但是您只需要从片段而不是适配器开始活动。
onClick
从片段:
Intent comment = new Intent(getActivity(), com.fooddoof.fuddict.comment.class);
startActivityForResult(comment, 1);
onBackPressed
在您的评论活动中:
@Override
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("maincommentcount",10);
returnIntent.putExtra("maincommentposition",20);
setResult(Activity.RESULT_OK,returnIntent);
finish();
// super.onBackPressed();
}
onActivityResult
在片段中:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
int mMaincommentcount = data.getIntExtra("maincommentcount", 0);
int mMaincommentposition = data.getIntExtra("maincommentposition", 0);
System.out.println("mMaincommentcount = " + mMaincommentcount + ", mMaincommentposition = " + mMaincommentposition);
}
}
}
推荐阅读
- plantuml - Mix classes and use cases in PlantUML diagram
- installation - MSYS2 安装程序
- javascript - 如何在 Google Apps 脚本中使用 MailApp 附加计算的 CSV
- plsql - 寻找阿拉伯语文本之间的相似性
- python - 如何从外部终止线程或在python的多处理中使用输入
- c++ - 从/到文件写入和读取提升属性树?
- matrix - 如何在谷歌数据工作室中绘制矩阵视觉图
- regex - 正则表达式捕获单个字符,该字符不捕获以它开头的所有单词
- excel - 需要减去不同的日期时间字段来捕获 TAT(周转时间)
- gcc - gcc 输出文件是什么样的,它究竟包含什么?