首页 > 解决方案 > 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值以显示. 但是当我回到. 我尝试访问它,但只能工作一段时间。我也将其声明为全局变量。FragementAdapterrecyclerViewfragmentOnCreateViewOnResumeArraylist

标签: javaandroidandroid-fragments

解决方案


你现在已经在使用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);
            }
        }
    }

推荐阅读