如何将额外内容传递给在RecyclerView OnClickListener内部调用的intent?

时间:2016-06-20 17:09:06

标签: android android-intent android-recyclerview

我在RecyclerView中实现了OnClickListener。单击特定项目时,必须从将要显示有关项目的详细信息的位置开始新活动。我该怎么办?

我的代码:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

private String[] data;
public Context context;

public RecyclerViewAdapter(String[] input, Context c) {
    data = input;
    context = c;
}

public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public MyOnItemClickListener listener;
    public TextView mTextView;
    public Context cont;

    public MyViewHolder(View v, MyOnItemClickListener l, Context c) {
        super(v);
        mTextView = (TextView) v.findViewById(R.id.info_text);
        listener = l;
        cont = c;
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        listener.startActivity(cont);
        /* below is my attempt that did not work */
        Intent intent = new Intent(cont, ItemInformationActivity.class);
        intent.putExtra("Text", mTextView.toString());
        cont.startActivity(intent);
    }

    public static interface MyOnItemClickListener {
        public void startActivity(Context c);
    }
}

@Override
public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view_item, parent, false);
    MyViewHolder vh = new MyViewHolder(v, new MyViewHolder.MyOnItemClickListener() {
        @Override
        public void startActivity(Context c) {
            Toast.makeText(c, "Item Pressed!", Toast.LENGTH_SHORT).show();
            /* tried the same here */
        }
    }, context);
    return vh;
}

@Override
public void onBindViewHolder(RecyclerViewAdapter.MyViewHolder holder, int position) {
    holder.mTextView.setText(data[position]);
}

@Override
public int getItemCount() {
    return data.length;
}
}

1 个答案:

答案 0 :(得分:1)

替换此行

intent.putExtra("Text", mTextView.toString());

intent.putExtra("Text", ((TextView) v.findViewById(R.id.info_text)).getText().toString());