1

Доброго времени суток! У меня есть статический ArrayList предметов, которые отображаются в SubjectListFragment в котором есть RecyclerView. Нужно чтобы по нажатию на элемент RecyclerView вызывался новый фрагмент с указанием позиции клика. Код FragmentSubjectList

public class SubjectListFragment extends Fragment implements AdapterView.OnItemClickListener{
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;


/**
 * Пустой конструктор
 */
public SubjectListFragment() {
}

// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static SubjectListFragment newInstance(int columnCount) {
    SubjectListFragment fragment = new SubjectListFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_COLUMN_COUNT, columnCount);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.d("SubjectListFragment", "Created!");

    if (getArguments() != null) {
        mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
    }
}

/**
 * Назначаем адаптер и заполняем View
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_subject_list, container, false);


    CardView cardView = (CardView) view.findViewById(R.id.cardViewSubject);

    // Set the adapter
    if (view instanceof RecyclerView) {
        Context context = view.getContext();
        RecyclerView recyclerView = (RecyclerView) view;
        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
        }
        recyclerView.setAdapter(new SubjectListRecyclerViewAdapter(MainActivity.subjectArrayList, mListener));
    }

    return view;
}


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

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

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    Log.d("OnItemClick", "Clicked!");

    FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
    Bundle bundle = new Bundle();
    bundle.putInt("id", position);
    fragmentTransaction.replace(R.id.FragmentHost, new NotesFragment());
    fragmentTransaction.commit();
}


/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p/>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnListFragmentInteractionListener {

    void onListFragmentInteraction(Subject subject);
}

} Я реализую интерфейс OnItemItemClick, но метод OnClick не вызывается. Код RecyclerView

public class SubjectListRecyclerViewAdapter extends RecyclerView.Adapter<SubjectListRecyclerViewAdapter.ViewHolder> {

private final  List<Subject> subjectList; //Список элементов
private final OnListFragmentInteractionListener mListener;

public SubjectListRecyclerViewAdapter(List<Subject> items, OnListFragmentInteractionListener listener) {
    subjectList = items;
    mListener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.fragment_subject, parent, false);

    return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.subject = subjectList.get(position);
    holder.subjectName.setText(subjectList.get(position).getName());

    holder.mView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (null != mListener) {
                // Notify the active callbacks interface (the activity, if the
                // fragment is attached to one) that an item has been selected.

                mListener.onListFragmentInteraction(holder.subject);

            }
        }
    });

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


public class ViewHolder extends RecyclerView.ViewHolder {

    public final View mView;

    public final TextView subjectName;
    public Subject subject;

    public ViewHolder(View view) {
        super(view);
        mView = view;

        subjectName = (TextView) view.findViewById(R.id.subjectName);
    }

    @Override
    public String toString() {
        return super.toString() + " '" + subjectName.getText() + "'";
    }


}

}

Заранее спасибо!

2
  • Метод onItemClick() интерфейса AdapterView.OnItemClickListener и не будет вызываться, потому что для RecyclerView этот интерфейс не определен. Вам нужно в RecyclerView реализовать собственный интерфейс-колбэк и определить для него метод передачи значения в фрагменте. При этом у вас имеется какой то интерфейс в фрагменте, но назначение его несколько туманно.
    – pavlofff
    16 июл 2017 в 9:56
  • Проблема решена.
    – Handen
    17 июл 2017 в 20:33

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.