Примечание: мои 2 действия имеют одно и то же имя и используют один и тот же макет, с той лишь разницей, что они находятся в разных каталогах и выполняют немного разные задачи.
Изначально я планировал использовать для приложения все фрагменты, но теперь решил использовать только один для первого выпуска, а над остальными работать позже, потому что нужно было обработать все сразу
Поэтому я хочу безопасно удалить нижний вид навигации и два других фрагмента (второй & третий фрагмент).
Сначала я уже пытался сделать это самостоятельно, удалив эти фрагменты и весь связанный с ними код, но получилось много ошибок, поэтому я решил принести его сюда, чтобы посмотреть, сможет ли кто-нибудь помочь с самым безопасным способом их удаления, чтобы мой первый фрагмент
мог продолжать работать без каких-либо проблем.
Он это приложение о погоде, поэтому я получаю текущие обновления города в первом фрагменте. Я должен был получать ежечасные и ежедневные обновления по второму и третьему фрагментам, но я приостановил свой план и сейчас хочу использовать только первый фрагмент.
Вот основные сведения коды:
Activity\HomeActivity:
Код: Выделить всё
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.nyc, R.drawable.lofoten_islands, R.drawable.parque, R.drawable.moraine_lake, R.drawable.eiffel_tower,
R.drawable.whitehaven_beach, R.drawable.london, R.drawable.cape_town, R.drawable.burj_al_arab,R.drawable.atuh_beach};
Timer _t;
private WeatherDataViewModel viewModel;
private AppBarConfiguration appBarConfiguration;
@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);
// Hiding default Drawer fragment that has the BottomNavView
navigationView.getMenu().findItem(R.id.main_id).setVisible(false);
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();
// Make hourly & daily tab unusable
bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
}
return false;
});
toggle.setToolbarNavigationClickListener(v -> {
// Enable the functionality of opening the side drawer, when the burger icon is clicked
toggle.setDrawerIndicatorEnabled(true);
navController.navigate(R.id.main_id);
});
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
// remove up button from all these fragments
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.main_id) // remove up button from all these fragments >> Keep up button in R.id.nav_setting, R.id.nav_slideshow
.setOpenableLayout(drawer)
.build();
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
// navController.addOnDestinationChangedListener((controller, destination, arguments) -> navController.popBackStack(destination.getId(), false));
// navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
// });
navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
// Hide/show top search bar
if (destination.getId() == R.id.main_id) {
Search.setVisibility(View.VISIBLE);
textfield.setVisibility(View.VISIBLE);
} else {
Search.setVisibility(View.GONE);
textfield.setVisibility(View.GONE);
}
// Fragments that you want to show the back button
if (destination.getId() == R.id.about_id || destination.getId() == R.id.privacy_policy_id) {
// Disable the functionality of opening the side drawer, when the burger icon is clicked
toggle.setDrawerIndicatorEnabled(false);
}
});
// For scheduling background image change
constraintLayout = findViewById(R.id.layout);
constraintLayout.setBackgroundResource(R.drawable.nyc);
_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 call = apiInterface.getWeatherData(name);
call.enqueue(new Callback() {
@Override
public void onResponse(@NonNull Call call, @NonNull Response 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 call, @NotNull Throwable t) {
t.printStackTrace();
}
});
}
});
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.about_id:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment,
new About()).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
}
}
@Override
protected void onPause () {
super.onPause();
if (viewModel.getMediaPlayer() != null)
viewModel.getMediaPlayer().pause();
}
@Override
protected void onResume () {
super.onResume();
if (viewModel.getMediaPlayer() != null) {
viewModel.getMediaPlayer().start();
viewModel.getMediaPlayer().setLooping(true);
}
}
@Override
public boolean onSupportNavigateUp() {
final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
assert navHostFragment != null;
final NavController navController = navHostFragment.getNavController();
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp(); // navigateUp tries to pop the backstack
}
}
Код: Выделить всё
public class HomeActivity extends AppCompatActivity {
private DrawerLayout drawer;
// Last update time, click sound, search button, search panel.
TextView timeField;
MediaPlayer player;
ImageView Search;
ConstraintLayout searchbar;
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.nyc, R.drawable.lofoten_islands, R.drawable.parque, R.drawable.moraine_lake, R.drawable.eiffel_tower,
R.drawable.whitehaven_beach, R.drawable.london, R.drawable.cape_town, R.drawable.burj_al_arab, R.drawable.atuh_beach};
Timer _t;
private WeatherDataViewModel viewModel;
private AppBarConfiguration appBarConfiguration;
@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);
// host 3 fragments along with bottom navigation.
final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
assert navHostFragment != null;
final NavController navController = navHostFragment.getNavController();
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
// remove up button from all these fragments
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.main_id) // remove up button from all these fragments >> Keep up button in R.id.nav_setting, R.id.nav_slideshow
.setOpenableLayout(drawer)
.build();
// Hiding default Drawer fragment that has the BottomNavView
navigationView.getMenu().findItem(R.id.main_id).setVisible(false);
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);
searchbar = findViewById(R.id.searchbar);
// find the id's of specific variables.
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
toggle.setToolbarNavigationClickListener(v -> {
// Enable the functionality of opening the side drawer, when the burger icon is clicked
toggle.setDrawerIndicatorEnabled(true);
navController.navigate(R.id.main_id);
});
navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
// Hide/show top search bar
if (destination.getId() == R.id.main_id) {
searchbar.setVisibility(View.VISIBLE);
toggle.setHomeAsUpIndicator(R.drawable.nav_back_arrow);
toggle.setDrawerIndicatorEnabled(true); //
Подробнее здесь: [url]https://stackoverflow.com/questions/73671129/remove-bottom-navigation-view-with-fragments[/url]