Creé un cajón de navegación personalizable desde cero (no usé el cajón predeterminado proporcionado por Android Studio). En el menú de la barra de navegación de mi aplicación meteorológica https://i.stack.imgur.com/SIjdx.jpg , cada vez que selecciono una opción en el menú (por ejemplo, configuración), muestra el contenido de la opción junto con la vista de navegación inferior y El contenido de la barra de herramientas de mi actividad, que se compone del icono de hamburguesa de navegación, el texto de edición y el botón de búsqueda (la actividad que aloja mis 3 fragmentos), lo que estropea la aplicación y hace que se vea muy fea, es decir, https://i.stack.imgur.com/gxj5n .jpg (De esa captura de pantalla, todo el contenido debería estar vacío si se implementa bien). El caso es el mismo para las otras opciones del menú de la barra. Todo lo que quiero es un espacio vacío para trabajar, quiero que la aplicación solo muestre el contenido de la barra de navegación sin el resto. Ejemplo; https://i.stack.imgur.com/3Jtga.png Por favor, ¿cómo debo hacer esto?
La vista del menú de navegación está controlada por este código (en la línea 185):
@Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.settings_id: getSupportFragmentManager().beginTransaction().replace(R.id.fragment, new Settings()).commit(); break; case R.id.ads_upgrade_id: getSupportFragmentManager().beginTransaction().replace(R.id.fragment, new Upgrade()).commit(); break; case R.id.privacy_policy_id: getSupportFragmentManager().beginTransaction().replace(R.id.fragment, new Privacy_Policy()).commit(); break; } drawer.closeDrawer(GravityCompat.START); return true; }"fragmento" allí representa que actualmente estoy usando la vista de contenedor de mi fragmento en mi actividad para mostrar el contenido del menú de navegación que sé que es incorrecto, entonces, ¿qué debo usar en reemplazo? Carezco de mucha experiencia ya que es la primera vez que construyo una aplicación y he pasado incansablemente 3 horas por mi cuenta tratando de resolver el problema que resultó abortivo.
Aquí está mi código de actividad:
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private DrawerLayout drawer; // Last update time, click sound, search button, search panel. TextView timeField; MediaPlayer player; ImageView Search; EditText textfield; // For scheduling background image change(using constraint layout, start counting from dubai, down to statue of liberty. ConstraintLayout constraintLayout; public static int count = 0; int[] drawable = new int[]{R.drawable.dubai, R.drawable.norway, R.drawable.eiffel_tower, R.drawable.hong_kong, R.drawable.statue_of_liberty, R.drawable.beijing, R.drawable.chicago, R.drawable.colombia, R.drawable.vienna,R.drawable.tokyo}; Timer _t; private WeatherDataViewModel viewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); // use home activity layout. Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Allow activity to make use of the toolbar drawer = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); viewModel = new ViewModelProvider(this).get(WeatherDataViewModel.class); // Trigger action to open & close navigation drawer ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar , R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); timeField = findViewById(R.id.textView9); Search = findViewById(R.id.imageView4); textfield = findViewById(R.id.textfield); // find the id's of specific variables. BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView); // host 3 fragments along with bottom navigation. final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment); assert navHostFragment != null; final NavController navController = navHostFragment.getNavController(); NavigationUI.setupWithNavController(bottomNavigationView, navController); // Make hourly & daily tab unusable bottomNavigationView.setOnNavigationItemSelectedListener(item -> { if (getSupportFragmentManager().getBackStackEntryCount() > 0) { getSupportFragmentManager().popBackStack(); } return false; }); navController.addOnDestinationChangedListener((controller, destination, arguments) -> navController.popBackStack(destination.getId(), false)); // For scheduling background image change constraintLayout = findViewById(R.id.layout); constraintLayout.setBackgroundResource(R.drawable.dubai); _t = new Timer(); _t.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // run on ui thread runOnUiThread(() -> { if (count < drawable.length) { constraintLayout.setBackgroundResource(drawable[count]); count = (count + 1) % drawable.length; } }); } }, 5000, 5000); Search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // make click sound when search button is clicked. player = MediaPlayer.create(HomeActivity.this, R.raw.click); player.start(); getWeatherData(textfield.getText().toString().trim()); // make use of some fragment's data Fragment currentFragment = navHostFragment.getChildFragmentManager().getFragments().get(0); if (currentFragment instanceof FirstFragment) { FirstFragment firstFragment = (FirstFragment) currentFragment; firstFragment.getWeatherData(textfield.getText().toString().trim()); } else if (currentFragment instanceof SecondFragment) { SecondFragment secondFragment = (SecondFragment) currentFragment; secondFragment.getWeatherData(textfield.getText().toString().trim()); } else if (currentFragment instanceof ThirdFragment) { ThirdFragment thirdFragment = (ThirdFragment) currentFragment; thirdFragment.getWeatherData(textfield.getText().toString().trim()); } } private void getWeatherData(String name) { ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class); Call<Example> call = apiInterface.getWeatherData(name); call.enqueue(new Callback<Example>() { @Override public void onResponse(@NonNull Call<Example> call, @NonNull Response<Example> response) { try { assert response.body() != null; timeField.setVisibility(View.VISIBLE); timeField.setText("First Updated:" + " " + response.body().getDt()); } catch (Exception e) { timeField.setVisibility(View.GONE); timeField.setText("First Updated: Unknown"); Log.e("TAG", "No City found"); Toast.makeText(HomeActivity.this, "No City found", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(@NotNull Call<Example> call, @NotNull Throwable t) { t.printStackTrace(); } }); } }); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.settings_id: getSupportFragmentManager().beginTransaction().replace(R.id.fragment, new Settings()).commit(); break; case R.id.ads_upgrade_id: getSupportFragmentManager().beginTransaction().replace(R.id.fragment, new Upgrade()).commit(); break; case R.id.privacy_policy_id: getSupportFragmentManager().beginTransaction().replace(R.id.fragment, new Privacy_Policy()).commit(); break; } drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onBackPressed() { if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); // Open/close drawer animation } } }En caso de que necesite algún otro código para investigar el problema, hágamelo saber. Solo estoy tratando de evitar publicar demasiado.
EDITAR :
Mi antiguo gráfico de navegación de pestañas inferiores:
<?xml version="1.0" encoding="utf-8"?> <navigation 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:id="@+id/my_nav" app:startDestination="@id/firstFragment"> <fragment android:id="@+id/firstFragment" android:name="com.viz.lightweatherforecast.FirstFragment" android:label="fragment_first" tools:layout="@layout/fragment_first" /> <fragment android:id="@+id/secondFragment" android:name="com.viz.lightpreciseweatherforecast.SecondFragment" android:label="fragment_second" tools:layout="@layout/fragment_second" /> <fragment android:id="@+id/thirdFragment" android:name="com.viz.lightpreciseweatherforecast.ThirdFragment" android:label="fragment_third" tools:layout="@layout/fragment_third" /> </navigation>Mi nuevo gráfico de barras de navegación:
<?xml version="1.0" encoding="utf-8"?> <navigation 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:id="@+id/bar_nav" app:startDestination="@id/firstFragment"> <fragment android:id="@+id/firstFragment" android:name="com.viz.lightweatherforecast.FirstFragment" android:label="fragment_first" tools:layout="@layout/fragment_first" /> <fragment android:id="@+id/settings_id" android:name="com.viz.lightweatherforecast.Settings" android:label="@string/settings" tools:layout="@layout/settings" /> <fragment android:id="@+id/ads_upgrade_id" android:name="com.viz.lightweatherforecast.Upgrade" android:label="@string/upgrade_to_remove_ads" tools:layout="@layout/upgrade" /> <fragment android:id="@+id/privacy_policy_id" android:name="com.viz.lightweatherforecast.Privacy_Policy" android:label="@string/privacy_policy" tools:layout="@layout/privacy_policy"/> </navigation>Creo que entendí muy bien tu problema (si no me equivoco). La cuestión es que el comportamiento que está obteniendo en este momento es el escenario normal. Está utilizando la misma actividad de host para alojar tanto el Navigation Drawer de navegación como los fragmentos de Bottom Navigation , por lo tanto, cuando intentó navegar a otro fragmento desde el mismo host, se muestra la presencia de la barra de NavBar inferior de la vista secundaria directa del host. Creo que puede resolver este problema de unas pocas formas lógicas diferentes pero bastante simples .
Settings . Al igual que startActivity(this, <some intent>) . Pero de esta manera, terminarás creando muchas actividades individuales.common_nav_graph y establecer algunas acciones con o sin argumentos para la navegación. Simplemente agregue common_nav_graph como un gráfico anidado dentro de su gráfico actual y configure una acción argumentada simple. Los argumentos lo ayudarán a navegar por las páginas/fragmentos deseados sin mostrar la bottom navigation bar .