如何通过RecyclerViewAdapter将数据从活动传递到片段?

时间:2019-04-16 10:19:42

标签: java android android-intent recycler-adapter

我在回收站视图适配器上使用startActivityForResult。然后,我想从新活动中按下来将值传递给附加了recyclerview的片段。

我尝试过:

RecyclerViewAdapter.java

@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) {


    myViewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(mContext, mData.get(i).getText(), Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(mContext, IntentActivity.class);

            Bundle bundle = new Bundle();
            bundle.putInt("Image",mData.get(i).getPhoto());
            bundle.putString("WebSite",mData.get(i).getWebSite());
            bundle.putInt("Heart",mData.get(i).getHeart());
            bundle.putInt("i",i);
            intent.putExtras(bundle);
            //mContext.startActivity(intent);
            ((Activity) mContext).startActivityForResult(intent,2);

        }
    });


    myViewHolder.love.setImageResource(mData.get(i).getHeart());
    myViewHolder.text.setText(mData.get(i).getText());
    myViewHolder.image.setImageResource(mData.get(i).getPhoto());
}

IntentActivity.java

@Override
public void onBackPressed() {
    super.onBackPressed();
    Toast.makeText(getApplication(),"back pressed", Toast.LENGTH_SHORT).show();

    Intent returnIntent = getIntent();
    returnIntent.putExtra("position",i);
    returnIntent.putExtra("isLoved",loved);
    setResult(RESULT_OK, returnIntent);
    finish();
}

然后在Fragment类上执行此操作:

PageOne.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 2) {
        if (resultCode == RESULT_OK) {
            String result = data.getStringExtra("isLoved");

            Toast.makeText(getActivity(),result,Toast.LENGTH_SHORT).show();


        }
    }
}

什么也没发生,Toast.makeText(getActivity(),result,Toast.LENGTH_SHORT).show();不会弹出。

1 个答案:

答案 0 :(得分:0)

onActivityResult很有可能吞噬了活动,请确保您在Activity中致电super.onActivityResult,如下所示:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data)
    ...
}