Запуск нового фрагмента из фрагмента с указанием позиции клика

303
17 июля 2017, 14:34

Доброго времени суток! У меня есть статический 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() + "'";
    }

}

}

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

READ ALSO
Приводит ли перекрестный вызов doGet() и doPost к deadlock?

Приводит ли перекрестный вызов doGet() и doPost к deadlock?

Во многих ресурсах можно найти вопрос для интервью о том как вызвать deadlock в сервлете, и везде говориться о том что нужно вызвать в теле doPost()...

274
Что плохого в моем коде тестового задания на java?

Что плохого в моем коде тестового задания на java?

Задача тестового: привести примеры использования ООП Что подтянуть? Критикуйте пожоще

276
Как вывести время без сдвига временной зоны

Как вывести время без сдвига временной зоны

Как вывести время без сдвига по временной зоне?

257