I am currently writing an app that includes a BottomNavigationBar (android studio)
but I got a problem:
I want the layouts to switch (or at least the TextViews inside each),
currently the navigation is not doing more than switching between single strings. so how can I make it work? please give me a step-by-step guide because I am fairly new to this whole stuff.
here's some code:
package com.john.doe.mycvasapp;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
public class Personal extends AppCompatActivity {
private TextView mTextMessage;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.personal:
mTextMessage.setText(R.string.personal1);
return true;
case R.id.school:
mTextMessage.setText(R.string.school1);
return true;
case R.id.work:
mTextMessage.setText(R.string.work1);
return true;
case R.id.skills:
mTextMessage.setText(R.string.skills1);
return true;
case R.id.lastly:
mTextMessage.setText(R.string.lastly1);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_persoenliche_daten);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
}
thanks for all the incoming help,
regards, guy from internet
Related
I used the basic "Navigation Drawer Acticity" in Anroid Studio when creating the new project. The fragments work well and I've managed to add new fragments and everything.
However, items in the drawer menu that direct you to a certain website don't work. I've tried different methods with public boolean onNavigationItemSelected(MenuItem item){} and nothing happens when I press the items.
It looks like this:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_moodle) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
return true;
}
return true;
}
As you can see I did nothing for the fragments to work since they work fine already but when I press the button "moodle", nothing happens.
What have I done wrong?
Here is my MainActivity:
package com.example.ustudy;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.widget.Toast;
import com.example.ustudy.ui.home.HomeFragment;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.example.ustudy.databinding.ActivityMainBinding;
import org.jetbrains.annotations.NotNull;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private AppBarConfiguration mAppBarConfiguration;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//required for the top bar to be clickable
setSupportActionBar(binding.appBarMain.toolbar);
//button in the bottom right corner
binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = binding.drawerLayout;
//Navigationview for the drawer (implemented in "activity_main.xml")
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
//each screen mentioned in the columns below (R.id.xy) will show the hamburger menu in the top left corner
//on screens, not included in the columns, there will be a "back arrow" instead of the ham. menu
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_nachricht, R.id.nav_lerngruppe, R.id.nav_lehrveranstaltung)
.setDrawerLayout(drawer)
.build();
//controls what happens when one of the items in the hamburger menu is clicked on
//go to "mobile_navigation.xml" to add screens to go to
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
//required to set up the hamburger menu icon and the back-arrow icon on the top bar(without it
//the user had to slide the side of the screen to open the menu)
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
//enables the items in the hamburger menu to go to a certain screen after clicking on them
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu (three dots on the right); this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
//enables the usage of the back-arrow on every screen
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(#NonNull #NotNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_moodle) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
return true;
}
return true;
}
}
Please, let me know if you need more!
I have a bottom navigation bar with 4 buttons. One of them is a back-button that just navigates back to the previously displayed fragment (I use a one-activity multiple-fragments approach). Basically everything works fine. Now I wanted to know whether it is possible not to navigate back to a certain fragment A? So basically whenever this Fragement A was the last fragment that was being displayed and the user clicks on the back-button, it should not navigate back but rather stay on the current fragment (and maybe display a small toast message).
So here you can see my main activity where the navigation is implemented:
package com.example.td.bapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import com.example.td.bapp.databinding.ActivityMainBinding;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
public class MainActivity extends AppCompatActivity {
public static DataBaseHelper myDB;
public static boolean veryFirstCreation = true;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
final NavController navController = Navigation.findNavController(this,
R.id.navHostfragment);
NavigationUI.setupWithNavController(binding.bottomNavigation, navController);
myDB=new DataBaseHelper(this);
if(veryFirstCreation) {
navController.navigate(R.id.FR_LanguageSelection);
veryFirstCreation = false;
}
// Define the bahaviour when clicking on items of the bottomNavigationBar; Overwrites the JetpackNavigation behaviour (automatic navigation using the id specified in the BottomNavigation XML menu file)
binding.bottomNavigation.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId()== R.id.BottomNavigation_Back) {
//Here I navigate back to the previous fragment
navController.navigateUp();
}
if (item.getItemId()== R.id.BottomNavigation_Language) {
navController.navigate(R.id.FR_LanguageSelection);
}
if (item.getItemId()== R.id.BottomNavigation_MyItems) {
navController.navigate(R.id.FR_MyItems);
}
if (item.getItemId()== R.id.BottomNavigation_Menu) {
navController.navigate(R.id.FR_Menu);
}
return true;
}
});
};
}
I'd appreciate every comment and would be quite thankful for your help.
You could use the SupportFragmentManager, with this you could know if your back stack contains at least one fragment. Use this in your back function (or in your onBackPressed if necessary)
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() ==1) {
Log.d("ppl","This is the last fragment. Show your message, poppup or whatever you want here")
} else if (fm.getBackStackEntryCount() >1) {
Log.d("ppl","the backstack still have more to show")
fm.popBackStackImmediate();
}
I created a bottom navigation for my app and was wondering how could I make it so when the user opens the app, it returns to the last fragment they were viewing? At the moment even if you just switch apps for a second, it reverts to the home page immediately. Thanks in advance!
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MenuItem;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomnav = findViewById(R.id.bottom_menu);
bottomnav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, new HomeFragment()).commit();
mediaPlayer = MediaPlayer.create(this, R.raw.clickandboop);
}
private final BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
mediaPlayer.start();
break;
case R.id.nav_favourites:
selectedFragment = new FavFragment();
mediaPlayer.start();
break;
case R.id.nav_trophies:
selectedFragment = new TrophiesFragment();
mediaPlayer.start();
break;
case R.id.nav_info:
selectedFragment = new InfoFragment();
mediaPlayer.start();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, selectedFragment).commit();
return true;
}
};
Fragments already restore you back to exactly where you were.
This means that you need to wrap your replace() call with a check of savedInstanceState == null to avoid destroying the just recreated Fragment:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_layout, new HomeFragment())
.commit();
}
Just use sharedprefs and store the last fragment that the user was in. Use the onStop callback of the fragment to store it.
When the user opens the application just check this value if it's not set open homefragment otherwise just open the last fragment based on the value you have in your shared preferences
I am currently making a program which opens a menu with a traditional menu button. There two different buttons: first should open the left side menu and the second is made for opening settings. The problem is both these buttons open the same menu. Please help me to make things so that each button opens its own menu.
I've made the main part of the app with a youtube video about these buttons. But there is a problem with them.
The following is the snapshot of menu that is opened with left side button:
And the following is the look of the app
And the following is the snapshot of the same menu opened with second button
Here is my code:
package com.danielliakhovetskyi.mainactivity;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MainActivity extends AppCompatActivity {
Menu menu;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
NavigationView navigationView;
MenuItem maths;
private boolean menuItemsAssigned = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Objects.requireNonNull(getSupportActionBar()).setBackgroundDrawable(new ColorDrawable
(Color.parseColor("#872be3"))); //making ActionBar light-coloured
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.abs_layout);
drawerLayout = findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = findViewById(R.id.navview);
navigationView.setItemTextAppearance(R.style.WithFont);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
Toast.makeText(MainActivity.this, "Default is clicked", Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
} else {
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.navigation_menu, menu);
/* this.menu = menu;
maths = menu.findItem(R.id.maths);
Logger.getGlobal().log(Level.INFO, "Maths Clicked");
Toast.makeText(this, "" + maths, Toast.LENGTH_SHORT).show();
maths.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
maths.setTitle("Maths");
Toast.makeText(MainActivity.this, "WORKS " + maths, Toast.LENGTH_SHORT).show();
Logger.getGlobal().log(Level.INFO, "Maths Clicked");
return false;
}
});
menuItemsAssigned = true;*/
return true;
}
}
In onCreateOptionsMenu() there is this line:
getMenuInflater().inflate(R.menu.navigation_menu, menu);
which apparently is wrong because it inflates the menu for the navigation drawer as the action bar menu.
Replace R.menu.navigation_menu with the menu for the action bar.
I am working on a project in Android Studio. My MainActivity shows the Actionbar. I created a new empty activity named Teachers. It shows the Actionbar when it's empty. I then created a webview. But when I input this webview code on Teachers activity, the Actionbar is not shown in the app (even though the webview works properly).
package com.codepade.shohel.eee7brur;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Teachers extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teachers);
webView = (WebView) findViewById(R.id.teachersweb);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/teachers/index.html");
webView.setWebViewClient(new WebViewClient());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack() == true){
webView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
in your Activity you can try getActionBar().show();