Up Arrow disabled on implementing App Bar with overflow menu - android

I am developing a sport timer app and new to android programming. I have implemented overflow menu. I am facing two issues:
Facing disappearing Up Arrow that is needed for navigation up in the hierarchy. Up arrow disappears as soon as one of the overflow menus is selected.
As up arrow is missing, I pressed back button, but the screen turns empty showing just the title in App Bar.
I just checked various postings on this missing up arrow in SO and outside. But was not able to get any clue to fix this. I could not see any difference between the code that I have and the solutions given. And for empty screen no clue available anywhere at all.
I frequently come to SO for help and indeed got many. Requesting SOians to help me here. Thanks.
<?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>
The java code of main activity is below
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();
}
}
Blank screen and missing up arrow image of the emulator is given as a link below (not allowed to post the image as such by SO)
Edit 1: After moving getSupportActionBar().setDisplayHomeAsUpEnabled(true); statement to onCreateOptionsMenu UP arrow is being displayed. But clicking UP arrow button shows blank screen. My issue #2 still remains. Need help here. Thanks.

I found solution for
issue 1: Adding getSupportActionBar().setDisplayHomeAsUpEnabled(true); in onCreateOptionsMenu
issue 2:
I came across a solution in https://medium.com/mobile-app-development-publication/learn-android-navigation-component-through-coding-79dc47b240b3 It worked perfectly well and solved white screen issue and also not using explicit method using fragment manager for traversing to another fragment. It was about linking menu items to navigation graph.

Related

Not being able to switch the toolbar for a different activity [Fixed]

I am working with two activities here and I want to switch the action bar from the default MainActivity to the one that I want to have in this particular activity that just has a + symbol to add stuff to what will be a notepad, but I can't catch the error, the logcat is empty and I am just trying to figure out how to change the action bar from the one that is currently showing to the one I want.
Here is my activity in which I am trying to get the different action bar to work:
package com.example.projetolinguagensprogramacao1;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
public class Notepad extends AppCompatActivity {
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notepad);
Toolbar toolbar2 = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar2);
recyclerView = findViewById(R.id.listOfnotes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId() == R.id.add_note){
Toast.makeText(this, "It's Working!", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
}
Here is the .xml of it:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.projetolinguagensprogramacao1.Notepad">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar2"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="#color/colorPrimary" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/listOfnotes"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar2" />
</androidx.constraintlayout.widget.ConstraintLayout>
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import android.view.MenuItem;
import android.view.Menu;
import com.google.android.material.navigation.NavigationView;
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 androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setNavigationViewListener();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_lembrete, R.id.nav_listacompra, R.id.nav_poupanca, R.id.nav_login, R.id.nav_notepad)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_login: {
startActivity(new Intent(this, Login.class));
break;
}
case R.id.nav_notepad: {
startActivity(new Intent(this, Notepad.class));
break;
}
}
return true;
}
private void setNavigationViewListener() {
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
}
And the .xml file for the + (plus) symbol that I want to show up on the action bar:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/add_note"
android:icon="#drawable/ic_add_symb"
android:title="Adicionar"
app:showAsAction="ifRoom" />
</menu>
Edit 1:
So instead of looking something like this:
It looks like this:
Edit 2: I tried using the same action bar in the main activity and it worked, so it just adds to my confusion as to why it isn't working in the Notepad activity.
Edit 3: Added Main Activity Code, I tried seeing if switching stuff on the onNavigationItemSelected() method and it still goes to image number 2. Maybe the problem is here I just can't find it.
Edit 4: I fixed it, I'm so sorry I am an idiot and didn't notice the blatant mistake I had, but thank you to all of you that answered and helped me.
you should create two menu file.xml
menu1(with its items) for MainActivity and menu2(with its items) for OtherActivity
then in each activity in onCreateOptionsMenu() method inflate its own menu.xml
check this code for short answer
check this for a mini project

My app is crashing when I add Bluetooth button [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I'm new in Android studio
I want to send data from Arduino to the android via Bluetooth HC-06
I begin my code from the template(Navigation Drawer Activity) of AndroidStudio.
At first everything was okay, but nightmares begin when I wanted to add Bluetooth button with the help SetOnClickListener to my code.
1. Its appearance changed from thisenter image description here
to this enter image description here. For clarity: Navigation bar and other tools disappeared, instead only home fragment is appeared.
2. When push the Bluetooth button on this fragment, my app closed.
I try to follow logcat , but can't fix the problem.
Please, help me with advice
Best Regard
p.s. Below is my MainActivity.java file
package com.example.myecg2;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private TextView Tekst;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Savollaringiz bo\'lsa Xat yozing", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
final int REQUEST_ENABLE_BT = 1;
setContentView(R.layout.fragment_home);
final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Button button =findViewById(R.id.button6);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (btAdapter == null) {
Tekst.setText("Bluetooth NOT support");
return;
} else {
if (btAdapter.isEnabled()) {
Tekst.setText("Bluetooth is currently in device discovery process.");
Tekst.append("\nPaired Devices are:");
Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
for (BluetoothDevice device : devices) {
Tekst.append("\nDevice" + device.getName() + "," + device);
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
}
);}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
And the content_main.xml file from the res/layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<TextView
android:id="#+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView8"
android:layout_width="394dp"
android:layout_height="218dp"
android:text="#string/matn"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button6" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="116dp"
android:text="#string/LeadI"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_home"/>
</androidx.constraintlayout.widget.ConstraintLayout>
and errors given in LogCat
2019-11-30 02:09:01.342 13088-13088/com.example.myecg2 D/AndroidRuntime: Shutting down VM
2019-11-30 02:09:01.343 13088-13088/com.example.myecg2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myecg2, PID: 13088
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.myecg2.MainActivity$2.onClick(MainActivity.java:75)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Tekst is null, i.e. you never instantiate that variable.
Your log says it right here:
java.lang.NullPointerException:
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.myecg2.MainActivity$2.onClick(MainActivity.java:75)
at ...
It even says the class the error is happening in, MainActivity, the method name its happening in onClick and the line of the error :75.
You are missing doing findViewById to instantiate your Tekst variable, in the onCreate before you attempt to access it (i.e access on line 75).
Sidenotes:
you call setContentView twice. You should not do that. Delete the second one.
Variable names in Java & Kotlin should start with a lowercase, to help you differentiate them from other things. Rename Tekst to tekst. Is that also a typo? perhaps it should be test and a better name to help you debug would be testTextView.

How to force the buttons in bottom navigation to be at the bottom in android studio

I am trying to use bottom navigation but the buttons or icons appears in the middle not in the bottom, I have use drawer navigation in the same activity i.e. I declare a drawer layout in the xml resource layout.
?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello"/>
</LinearLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="168dp"
android:layout_height="168dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
<android.support.design.widget.NavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:menu="#menu/drawer"
android:layout_gravity="start">
</android.support.design.widget.NavigationView>
The code of this activity:
package com.example.welcome.madrasti;
import android.content.ClipData;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
Intent intent1;
private DrawerLayout d;
private ActionBarDrawerToggle a;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_dashboard:
return true;
case R.id.navigation_home:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
d = (DrawerLayout) findViewById(R.id.container);
a= new ActionBarDrawerToggle(MainActivity.this,d,R.string.open,R.string.close);
d.addDrawerListener(a);
a.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
intent1= new Intent(getApplicationContext(),MapsActivity.class);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(a.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
}
Is there any idea ?. I have got the bottom navigation as follows : here
Changing padding at the Bottom to small a value like:
android:paddingBottom="2dp"
Also your BottomNavigationView appears to be a square of 168dp size. Is this intentionally? Change the height it or view its layout bounds. It may be very big by itself like a square.

Default fragment in activity

I've seen many posts on this matter, but I can't figure it out for my code. I have created a tabbed activity and set three buttons at the bottom. The buttons switch between different fragments. A button in a MainActivity opens this tabbed activity, but the problem is that the fragment layout is empty (see image below).
The buttons work perfectly and send me to the right fragments, but when it opens, no fragments are loaded.
The code, which I build following an YouTube tutorial looks like this:
TabbedActivity.class
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class TabbedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed_activity);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
int intentFragment = getIntent().getExtras().getInt("frgToLoad");
switch (item.getItemId()) {
case R.id.navigation_home:
transaction.replace(R.id.content,new Fragment_B1()).commit();
/* mTextMessage.setText(R.string.title_home);*/
return true;
case R.id.navigation_dashboard:
transaction.replace(R.id.content,new Fragment_B2()).commit();
/*mTextMessage.setText(R.string.title_dashboard);*/
return true;
case R.id.navigation_notifications:
transaction.replace(R.id.content,new Fragment_B3()).commit();
/*mTextMessage.setText(R.string.title_notifications);*/
return true;
}
return false;
}
};
}
The fragments have the same code pattern inside, which is basic and it makes no point to add it here. The xml of the TabbedActivity looks like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="TabbedActivity">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toBottomOf="#+id/appbar">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
Can anyone help me to figure out how to open Fragment_B1 by default? I have tried adding the code from the best answer from here, but still doesn't work.
You can just added the original fragment direct on the onCreate, like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed_activity);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
if(savedInstanceState == null) {
getSupportFragmentManager().
beginTransaction().replace(R.id.content,new Fragment_B1()).commit();
}
}
In the last add, navigation.setSelectedItemId(navigation_home);

Android Bottom Navigation

I have been implementing a bottom navigation bar into my app, the problem is no matter which activity I am on the dashboard icon is the highlighted one. How do I get it so whichever activity I am on is the highlighted one?
public class Dashboard extends AppCompatActivity
implements View.OnClickListener
{
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener()
{
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item)
{
switch (item.getItemId())
{
case R.id.navigation_request:
Intent r = new Intent(Dashboard.this, Request.class);
startActivity(r);
finish();
break;
case R.id.navigation_settings:
Intent s = new Intent(Dashboard.this, AppSettings.class);
startActivity(s);
finish();
break;
}
return false;
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
Here is my XML Menu file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/title_home" />
<item
android:id="#+id/navigation_request"
android:icon="#drawable/ic_request_icon"
android:title="#string/title_request" />
<item
android:id="#+id/navigation_settings"
android:icon="#drawable/ic_icon_settings"
android:title="#string/title_settings" />
</menu>
Here is how I use the navigation in my activity_dashboard
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<!-- ONLY TEXTVIEWS ARE HERE -->
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/navigation" />
</LinearLayout>
Using many different Activity instances that all duplicate the BottomNavigationView and its associated code (like the OnNavigationItemSelectedListener etc) is not recommended. Instead, you would generally use a single Activity that hosts the BottomNavigationView as well as multiple Fragment instances that are .replace()d into your content area as the user interacts with the BottomNavigationView.
That being said, let's see if we can solve your problem.
There are two pieces to this puzzle. The first is simple: you have to indicate which item in your BottomNavigationView should be selected. This can be achieved by calling setSelectedItemId(). Add something like this to your onCreate() method.
navigation.setSelectedItemId(R.id.navigation_settings);
The second is a little more complicated. When you call setSelectedItemId(), the system is going to behave as though a user had tapped on that item. In other words, your OnNavigationItemSelectedListener will be triggered.
Looking at your posted listener, I notice that you always return false. If you check the documentation for onNavigationItemSelected(), you will find
Returns:
true to display the item as the selected item and false if the item should not be selected
So the call to setSelectedItemId() won't work without also changing your listener to return true.
You could still solve the problem with just a setSelectedItemId() call if you place that call before your setOnNavigationItemSelectedListener() call, but that's just masking the problem. It'd be better to fix your listener to return true in cases where you want the tapped item to appear as selected.
Step - 1 put below code into app level Build.gradle
implementation 'androidx.navigation:navigation-fragment:2.3.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.navigation:navigation-ui:2.3.0'
Step - 2 put below code into activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="?attr/actionBarSize">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step - 3 put below code into menu/bottom_nav_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/title_home" />
<item
android:id="#+id/navigation_dashboard"
android:icon="#drawable/ic_dashboard_black_24dp"
android:title="Orders" />
<item
android:id="#+id/navigation_notifications"
android:icon="#drawable/ic_notifications_black_24dp"
android:title="Services" />
<item
android:id="#+id/navigation_account"
android:icon="#drawable/ic_notifications_black_24dp"
android:title="Account" />
</menu>
Step - 4 put below code into MainActivity.java
import android.os.Bundle;
import android.view.MenuItem;
import com.example.bottomnavigationdemo.ui.account.AccountFragment;
import com.example.bottomnavigationdemo.ui.dashboard.DashboardFragment;
import com.example.bottomnavigationdemo.ui.home.HomeFragment;
import com.example.bottomnavigationdemo.ui.notifications.NotificationsFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
Fragment fragment = new HomeFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment, fragment, fragment.getClass().getSimpleName())
.commit();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, fragment, fragment.getClass().getSimpleName());
transaction.commit();
return true;
case R.id.navigation_dashboard:
Fragment fragment2 = new DashboardFragment();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, fragment2, fragment2.getClass().getSimpleName());
transaction.commit();
return true;
case R.id.navigation_notifications:
Fragment fragment3 = new NotificationsFragment();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, fragment3, fragment3.getClass().getSimpleName());
transaction.commit();
return true;
case R.id.navigation_account:
Fragment fragment4 = new AccountFragment();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, fragment4, fragment4.getClass().getSimpleName());
transaction.commit();
return true;
}
return true;
}
});
}
}
Step - 5 put below code into HomeFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.bottomnavigationdemo.R;
import com.example.bottomnavigationdemo.ui.dashboard.DashboardFragment;
public class HomeFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
}
}
Just use method setSelectedItemId(int id) which let's you mark an item as selected as if it was tapped.
Like this:
BottomNavigationView bottomNavigationView;
bottomNavigationView = (BottomNavigationView)
findViewById(R.id.bottomNavigationView);
bottomNavigationView.setSelectedItemId(R.id.my_menu_item_id);

Categories

Resources