我想在“回收者”视图中单击“项目”时传递数据先前的活动,并将其显示在“编辑文本”上。

这是我用来将数据从列表视图传递到上一个活动的代码

我想对Recyclerview做同样的事情

//调用第二个活动

public static final int REQUEST_CODE = 100;
Intent dateintent = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(dateintent, REQUEST_CODE);


// onview of listview将数据传递回上一个活动

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView txt = (TextView) view.findViewById(R.id.textView);
                String str = txt.getText().toString();

                Intent intent = new Intent();
                intent.putExtra("data",str);
                setResult(RESULT_OK,intent);
                finish();

            }


});

//获取数据后,在第一个活动编辑框中显示数据

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            String data= data.getStringExtra("data");
            if (data!= null) {
                edittext.setText(data);
            }
        }
    }


}

最佳答案

首先创建此接口

public interface RunnableValue {

public void run(Object obj);
}


2.此MainActivity添加

 RunnableValue run=new RunnableValue() {
        @Override
        public Bundle run(Object obj) {

             String str = obj.toString();

            Intent intent = new Intent();
            intent.putExtra("data",str);
            setResult(RESULT_OK,intent);
            finish();
          }
    };
    mAdapter = new SearchAdapter(dataSet,run);



此RecyclerView适配器

public SearchAdapter(List<String>  dataSet,RunnableValue runnableValue) {
    mDataSet = dataSet;
    this.runnableValue=runnableValue;
}
public static class SearchHolder extends RecyclerView.ViewHolder {
private final TextView textView;

public SearchHolder(View v) {
    super(v);

    v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            runnableValue.run(getTextView().toString());
        }
    });
    textView = (TextView) v.findViewById(R.id.txtSearchItem);
}

public TextView getTextView() {
    return textView;
}


}

09-26 08:28