当前位置: 首页 > 知识库问答 >
问题:

如何将数据从RecycerView适配器传递或发送到片段

曾山
2023-03-14

exampleAdapter.java

public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
    private ArrayList<ExampleItem> mExampleList;
    @NonNull
    @Override
    public ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View v=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.example_item,viewGroup,false);
        ExampleViewHolder evh=new ExampleViewHolder(v);
        return evh;
    }
    @Override
    public void onBindViewHolder(@NonNull ExampleViewHolder exampleViewHolder, int i) {
        final ExampleItem currentItem=mExampleList.get(i);
        exampleViewHolder.mTextView.setText(currentItem.getmText());
        exampleViewHolder.mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // pass the data to the fragment
            }
        });
    }
    @Override
    public int getItemCount() {
        return mExampleList.size();
    }
    public static class ExampleViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextView;
        public ExampleViewHolder(@NonNull View itemView) {
            super(itemView);
            mTextView=itemView.findViewById(R.id.texttitle);
        }
    }
    public ExampleAdapter(ArrayList<ExampleItem> exampleList){
              this.mExampleList=exampleList;
}
}

共有1个答案

李法
2023-03-14

你有两个选择;

使用SharedPreferences:

Context myContext = exampleViewHolder.itemView.getContext()

SharedPreferences.Editor editor = getSharedPreferences("DeviceToken", MODE_PRIVATE).edit();
editor.putString("YourKeyNameHere", currentItem.getmText()); // or add toString() after if needed
editor.apply();

获取:

SharedPreferences prefs = getSharedPreferences("DeviceToken", MODE_PRIVATE);
String deviceToken = prefs.getString("YourKeyNameHere", null); // get it here
Intent intent = new Intent(myContext , SignoutActivity.class);
intent.putExtra("EXTRA_TEXT", currentItem.getmText());
startActivity(intent); // if needed, add myContext before starting myContext.startActivity...
String extraText = getIntent().getStringExtra("EXTRA_TEXT");
 类似资料: