Стрелка вверх отключена при реализации панели приложений с меню переполнения

#android #android-fragments #android-appbarlayout

Вопрос:

Я разрабатываю приложение для спортивного таймера и новичок в программировании на Android. Я реализовал меню переполнения. Я сталкиваюсь с двумя проблемами:

  1. Перед исчезающей стрелкой вверх, которая необходима для навигации вверх по иерархии. Стрелка вверх исчезает, как только выбирается одно из меню переполнения.
  2. Поскольку стрелка вверх отсутствует, я нажал кнопку «Назад», но экран становится пустым, показывая только заголовок в панели приложений.

Я только что проверил различные публикации по этой отсутствующей стрелке вверх в SO и outside. Но не смог получить никакой подсказки, чтобы исправить это. Я не видел никакой разницы между имеющимся у меня кодом и приведенными решениями. А для пустого экрана вообще нигде нет подсказки.

Я часто обращаюсь к SO за помощью и действительно получил много. Прошу SOians помочь мне здесь. Спасибо.

 <?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="visible"
    tools:context=".MainActivity">

    <TextView
        android:id="@ id/textView"
        android:layout_width="215dp"
        android:layout_height="48dp"
        android:background="@color/teal_200"
        android:text="@string/app_name"
        android:textAlignment="center"
        android:textAllCaps="true"
        android:textColor="@color/black"
        android:textSize="48sp"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_anchor="@ id/toolbar"
        app:layout_anchorGravity="center" />

    <androidx.appcompat.widget.Toolbar
        android:id="@ id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="69dp"
        android:background="@color/white"
        app:popupTheme="@style/Theme.PTimer.PopupOverlay" />


    <include
        android:id="@ id/include"
        layout="@layout/content_main"
        android:layout_height="match_parent"
        app:layout_anchor="@ id/include"
        app:layout_anchorGravity="center" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
 

Java-код основного действия приведен ниже

 package com.example.ptimer;

import android.content.Intent;
import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.ptimer.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

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

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setSupportActionBar(binding.toolbar);
 
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        FragmentManager fragmentManager = this.getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        switch (id) {
            case R.id.action_settings:
                Fragment fragmentS = new  SettingsFragment();
                fragmentTransaction.replace(R.id.nav_host_fragment_content_main, fragmentS);
                fragmentTransaction.setReorderingAllowed(true);
                fragmentTransaction.addToBackStack(null);
                break;
            case R.id.action_kyc:
                Fragment fragmentK = new KnowYourCapacity_Fragment();
                fragmentTransaction.replace(R.id.nav_host_fragment_content_main, fragmentK);
                break;
            case R.id.action_about:
                Fragment fragmentA = new HelpFragment();
                Bundle bundle = new Bundle();
                bundle.putString("help_desc", getResources().getString(R.string.pBasics_desc));
                bundle.putString("help_image","basic");
                fragmentA.setArguments(bundle);
                fragmentTransaction.replace(R.id.nav_host_fragment_content_main, fragmentA);
                break;
            default:
                break;
        }

        fragmentTransaction.commit();
        
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        onBackPressed();
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

}
 

Пустой экран и отсутствующее изображение эмулятора со стрелкой вверх приведены по ссылке ниже (SO не разрешает размещать изображение как таковое)

Редактировать 1: после перемещения getSupportActionBar().setDisplayHomeAsUpEnabled(true); инструкции onCreateOptionsMenu отображается стрелка ВВЕРХ. Но при нажатии кнопки со стрелкой ВВЕРХ отображается пустой экран. Моя проблема № 2 все еще остается. Здесь нужна помощь. Спасибо.

Ответ №1:

Я нашел решение для

проблема 1: добавление getSupportActionBar().setDisplayHomeAsUpEnabled(true); в onCreateOptionsMenu проблема 2: я наткнулся на решение в https://medium.com/mobile-app-development-publication/learn-android-navigation-component-through-coding-79dc47b240b3 Он работал отлично и решил проблему с белым экраном, а также не использовал явный метод с использованием диспетчера фрагментов для перехода к другому фрагменту. Речь шла о привязке пунктов меню к графику навигации.