单击CardView + RecyclerView时如何打开新片段

时间:2018-05-01 13:10:59

标签: android recycler-adapter android-cardview

在我的应用程序中,我有15张cardview,现在我想在点击cardview时显示一个片段,因为我有15个片段。

RecyclerViewAdapter.java

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

        private Context mContext;
        private List<reminder> mData;

        public RecyclerviewAdapter(Context mContext, List<reminder> mData) {
            this.mContext = mContext;
            this.mData = mData;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view;
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            view = inflater.inflate(R.layout.cardview, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            holder.mTextView.setText(mData.get(position).getmTitle());
            holder.mImageView.setImageResource(mData.get(position).getmImages());
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }

        public static class MyViewHolder extends RecyclerView.ViewHolder {

            TextView mTextView;
            ImageView mImageView;

            public MyViewHolder(View itemView) {
                super(itemView);

                mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
                mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);

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

                        switch (getAdapterPosition()) {
                            case 0 :

    //                            "What Should I do here"
                        }
                    }
                });

            }
        }
    }

Reminders.java

public class Reminders extends Fragment {

private OnFragmentInteractionListener mListener;
List<reminder> lstreminder;

public Reminders() {

}

public static Reminders newInstance(String param1, String param2) {
    Reminders fragment = new Reminders();
    Bundle args = new Bundle();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);

        lstreminder = new ArrayList<>();
        lstreminder.add(new reminder("Alarm",R.drawable.alarms));
        lstreminder.add(new reminder("Birthday",R.drawable.birthdays));
        lstreminder.add(new reminder("Anniversary",R.drawable.anniversaries));
        lstreminder.add(new reminder("Buy Gifts",R.drawable.buygift));
        lstreminder.add(new reminder("Bill Payments",R.drawable.billpayments));
        lstreminder.add(new reminder("Call / SMS",R.drawable.call));
        lstreminder.add(new reminder("Recharges",R.drawable.recharges));
        lstreminder.add(new reminder("Meetings",R.drawable.meetings));
        lstreminder.add(new reminder("Insurance",R.drawable.insurances));
        lstreminder.add(new reminder("Exams",R.drawable.exams));
        lstreminder.add(new reminder("Holidays",R.drawable.holidays));
        lstreminder.add(new reminder("Medical",R.drawable.medical));
        lstreminder.add(new reminder("Purchase",R.drawable.purchase));
        lstreminder.add(new reminder("Travel",R.drawable.travel));
        lstreminder.add(new reminder("Shows",R.drawable.shows));

    RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.mRecyclerView_id);
    RecyclerviewAdapter recyclerviewAdapter = new RecyclerviewAdapter(getActivity(),lstreminder);
    recyclerviewAdapter.setOnItemClickListner(new RecyclerviewAdapter.onItemClickListner() {
        @Override
        public void onClick(reminder str) {

        }
    });
    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
    recyclerView.setAdapter(recyclerviewAdapter);

    return rootView;
}

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    void onFragmentInteraction(Uri uri);
}

}

图像 enter image description here

这里的交换机案例我想根据适配器的位置打开新的片段。

有可能请指导我解决,或者如果我走错路,请指导我......

2 个答案:

答案 0 :(得分:1)

在循环器视图适配器中创建接口,如下面的代码..

onItemClickListner onItemClickListner;

public void setOnItemClickListner(RecyclerViewAdpater.onItemClickListner onItemClickListner) {
    this.onItemClickListner = onItemClickListner;
}

public interface onItemClickListner {
    void onClick(String str);//pass your object types.
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
    // below code handle click event on recycler view item.
    String data=mStringList.get(position);

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onItemClickListner.onClick(data);
        }
    });
}

您的密码..

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

private Context mContext;
private List<reminder> mData;

onItemClickListner onItemClickListner;

public void setOnItemClickListner(onItemClickListner onItemClickListner) {
    this.onItemClickListner = onItemClickListner;
}

public interface onItemClickListner {
    void onClick(reminder str);//pass your object types.
}
public RecyclerviewAdapter(Context mContext, List<reminder> mData) {
    this.mContext = mContext;
    this.mData = mData;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view;
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    view = inflater.inflate(R.layout.cardview, parent, false);
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    reminder data=mData.get(position);
    holder.mTextView.setText(mData.get(position).getmTitle());
    holder.mImageView.setImageResource(mData.get(position).getmImages());
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onItemClickListner.onClick(data);
        }
    });
}

@Override
public int getItemCount() {
    return mData.size();
}

public static class MyViewHolder extends RecyclerView.ViewHolder {

    TextView mTextView;
    ImageView mImageView;

    public MyViewHolder(View itemView) {
        super(itemView);

        mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
        mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);
    }
}

}

然后在定义适配器值并绑定到recycleler视图调用下面的代码..在活动中将适配器绑定到recycleler视图。

       recyclerViewAdpater.setOnItemClickListner(new RecyclerViewAdpater.onItemClickListner() {
       @Override
       public void onClick(String str) {
           // here call your fragment 

       }
   });

你的片段代码..

public class Reminders extends Fragment {

    private OnFragmentInteractionListener mListener;
    List<reminder> lstreminder;

    public Reminders() {

    }

    public static Reminders newInstance(String param1, String param2) {
        Reminders fragment = new Reminders();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);

            lstreminder = new ArrayList<>();
            lstreminder.add(new reminder("Alarm",R.drawable.alarms));
            lstreminder.add(new reminder("Birthday",R.drawable.birthdays));
            lstreminder.add(new reminder("Anniversary",R.drawable.anniversaries));
            lstreminder.add(new reminder("Buy Gifts",R.drawable.buygift));
            lstreminder.add(new reminder("Bill Payments",R.drawable.billpayments));
            lstreminder.add(new reminder("Call / SMS",R.drawable.call));
            lstreminder.add(new reminder("Recharges",R.drawable.recharges));
            lstreminder.add(new reminder("Meetings",R.drawable.meetings));
            lstreminder.add(new reminder("Insurance",R.drawable.insurances));
            lstreminder.add(new reminder("Exams",R.drawable.exams));
            lstreminder.add(new reminder("Holidays",R.drawable.holidays));
            lstreminder.add(new reminder("Medical",R.drawable.medical));
            lstreminder.add(new reminder("Purchase",R.drawable.purchase));
            lstreminder.add(new reminder("Travel",R.drawable.travel));
            lstreminder.add(new reminder("Shows",R.drawable.shows));

        RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.mRecyclerView_id);
        RecyclerviewAdapter recyclerviewAdapter = new RecyclerviewAdapter(getActivity(),lstreminder);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
        recyclerView.setAdapter(recyclerviewAdapter);
        recyclerviewAdapter.setOnItemClickListner(new RecyclerviewAdapter.onItemClickListner() {
            @Override
            public void onClick(reminder str) {
                // here str is click item value in recyclerview.
                // here perform your operation . str is give object reminder pojo class of selected item on recyclerview. 

    // below code you can make condition and check any value.
    if(str.getItemName().equals("xyz")){
        Fragment fragment = new MainFragment();// here give your fragment.
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
    }
    else if(str.getItemName().equals("ayx")){
        Fragment fragment = new HomeFragment();// here give your fragment.
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();

    }


               recyclerviewAdapter.notifyDataSetChanged();

            }
        });
        return rootView;
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

}

答案 1 :(得分:1)

试试这样:

public class NewAdapter extends RecyclerView.Adapter<NewAdapter.MyViewHolder> {
    Context context;
    LayoutInflater inflater;
    Activity activity;
    View view;
    RecyclerView recyclerViewNew;
    private ArrayList<reminder> mData;

    public NewAdapter(RecyclerView recyclerView, Context context, ArrayList<reminder>
            mData, Activity activity) {
        this.context = context;
        this.mData = mData;
        this.activity = activity;
        inflater = LayoutInflater.from(this.context);
        this.recyclerViewNew = recyclerView;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_cases_fragment, parent, false);

        MyViewHolder sectionViewHolder = new MyViewHolder(view);
        return sectionViewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        final int pos = position;
        holder.mTextView.setText(mData.get(position).getmTitle());
        holder.mImageView.setImageResource(mData.get(position).getmImages());
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context = view.getContext();
                Intent intent = new Intent();
                switch (pos) {
                    case 0:
                        AppCompatActivity activity = (AppCompatActivity) view.getContext();
                        Fragment myFragment = new MyFragment();
                        activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();
                        break;
                }

            }
        });
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView mTextView;
        ImageView mImageView;
        CardView cardView;

        public MyViewHolder(View itemView) {
            super(itemView);

            mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
            mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);
            cardView = (CardView) itemView.findViewById(R.id.cardView);
        }
    }
}

希望这会对你有所帮助。