Контекстное меню android не подключается

186
21 декабря 2019, 06:00

пытаюсь подключить контекстное меню к элементам списка, но ничего не происходит, в чем может быть проблема?

public class DetailsFragment extends Fragment {
    public void onViewCreated(View view, Bundle savedInstanceState) {
        plansList = (ListView) this.getActivity().findViewById(R.id.list_item);
        registerForContextMenu(plansList);
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getActivity().getMenuInflater();
        inflater.inflate(R.menu.context_menu_details, menu);
    }
}

Также добавил следующий код, тоже не работает:

    plansList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            CharSequence message = "Нажатие";
            Toast toast = Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    });

Использую свой адаптер, наследующийся от ArrayAdapter:

public class PlanAdapter extends ArrayAdapter<Plan> {
private LayoutInflater inflater;
private int layout;
private List<Plan> plans;
public PlanAdapter(Context context, int resource, List<Plan> plans) {
    super(context, resource, plans);
    this.plans = plans;
    this.layout = resource;
    this.inflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent) {
    View view = inflater.inflate(this.layout, parent, false);
    TextView nameView = (TextView) view.findViewById(R.id.name);
    TextView durationOfProcedureView = (TextView) view.findViewById(R.id.description);
    TextView timeView = (TextView) view.findViewById(R.id.time);
    TextView durationOfTreatmentView = (TextView) view.findViewById(R.id.dureationOfTreatment);
    CheckBox include = (CheckBox) view.findViewById(R.id.include);
    TextView interval = (TextView) view.findViewById(R.id.frequency);

    Plan plan = plans.get(position);
    nameView.setText(plan.getName());
    timeView.setText(plan.getTimeString());
    durationOfTreatmentView.setText(String.format(view.getResources().getString(R.string.durationOfTreatment), plan.getCountMadeProcedures(), plan.getDurationOfTreatment()));
    durationOfProcedureView.setText(String.format(view.getResources().getString(R.string.durationOfProcedure), plan.getDurationOfProcedure()));
    include.setChecked(plan.isIncluded());
    interval.setText(String.format(view.getResources().getString(R.string.every_day), plan.getInterval()));
    return view;
}
}
Answer 1

Как оказалось, в разметке элемента списка необходимо добавить блокировку фокусировки: android:descendantFocusability="blocksDescendants". В общем виде:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp"
    android:descendantFocusability="blocksDescendants">
    ...
</LinearLayout>
READ ALSO
Как получить самую частую гласную букву в строке

Как получить самую частую гласную букву в строке

Написал такой код, но с его помощью я получаю число повторений буквы в строке, как получить саму букву? никак не могу сообразить

163
Синхронизаниция по Integer в Java

Синхронизаниция по Integer в Java

Есть следующая учебная программка

146
Из активити не обновляется RecyclerView во фрагменте

Из активити не обновляется RecyclerView во фрагменте

При нажатии кнопки меню в MainActivity обновляются данные, изпользуемые в RecyclerViewСам рецайклер сидит во фрагменте, пытаюсь сообщить ему, что данные...

140