How to coordinate a Navigation Drawer with a Buttom Navigation View - java

I'm fairly new to android dev. I'm checking the material design library and I've implemented a navigation drawer with a bottom navigation to navigate easily through fragments. Both components work just fine but I don't how to coordinate the navigation with both components. For example when a fragment is toggled on the navigation drawer it changed the layout but the button navigation selected item is not changed with it.
How can I solve this issue and link both components to work with each other and sync the changed selected item?
This is what my java file looks like and here's link for the whole project on GitHub: https://github.com/mreek/NavigationDrawer
Thank you in advance.
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private TextView appBarTV;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent= new Intent(this,IntroActivity.class);
startActivity(intent);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
appBarTV = findViewById(R.id.appbar_text_view);
ImageButton menuRight = findViewById(R.id.leftRight);
menuRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
});
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = MainFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = AccountFragment.newInstance();
break;
case R.id.action_item3:
selectedFragment = SellFragment.newInstance();
break;
case R.id.action_item4:
selectedFragment = ChatFragment.newInstance();
break;
case R.id.action_item5:
selectedFragment = NotificationFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.f_container, selectedFragment);
transaction.commit();
return true;
}
});
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.f_container, MainFragment.newInstance());
transaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
drawer.closeDrawers();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
int id = item.getItemId();
if (id == R.id.nav_camera) {
MainFragment fragment = new MainFragment();
ft.replace(R.id.f_container, fragment);
ft.commit();
} else if (id == R.id.nav_gallery) {
//appBarTV.setText("Fragment With Tabs");
ChatFragment fragment = new ChatFragment();
ft.replace(R.id.f_container, fragment);
ft.commit();
} else if (id == R.id.nav_slideshow) {
AccountFragment fragmentTab = new AccountFragment();
ft.replace(R.id.f_container, fragmentTab);
ft.commit();
} else if (id == R.id.nav_share) {
Toast.makeText(this, "Partager", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_send) {
Toast.makeText(this, "Rate 5 stars", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
<?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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/app_bar_main" />
<FrameLayout
android:id="#+id/f_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="3dp"
android:background="#color/white"
app:itemIconTint="#color/blue"
app:itemTextColor="#color/blue"
app:menu="#menu/bottom_navigation_items" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer"
app:itemTextColor="#color/black"/>
</android.support.v4.widget.DrawerLayout>

First of all you should avoid recreating fragments when user selected a tab from bottom navigation. You should keep your fragments as private variables:
private DrawerLayout drawer;
private BottomNavigationView bottomNavigationView;
private MainFragment mainFragment = MainFragment.newInstance();
private AccountFragment accountFragment = AccountFragment.newInstance();
private SellFragment sellFragment = SellFragment.newInstance();
private ChatFragment chatFragment = ChatFragment.newInstance();
private NotificationFragment notificationFragment = NotificationFragment.newInstance();
When user selects a tab just swich to that fragment:
bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_announces:
selectedFragment = mainFragment;
break;
case R.id.action_account:
selectedFragment = accountFragment;
break;
case R.id.action_sell:
selectedFragment = sellFragment;
break;
case R.id.action_chat:
selectedFragment = chatFragment;
break;
case R.id.action_notifications:
selectedFragment = notificationFragment;
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (selectedFragment != null) {
transaction.replace(R.id.f_container, selectedFragment);
transaction.commit();
}
return true;
});
When user selects a tab using navigation menu swich to required fragment:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawer.closeDrawers();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (item.getItemId()) {
case R.id.nav_announces:
bottomNavigationView.setSelectedItemId(R.id.action_announces);
ft.replace(R.id.f_container, mainFragment);
break;
case R.id.nav_account:
bottomNavigationView.setSelectedItemId(R.id.action_account);
ft.replace(R.id.f_container, accountFragment);
break;
case R.id.nav_sell:
bottomNavigationView.setSelectedItemId(R.id.action_sell);
ft.replace(R.id.f_container, sellFragment);
break;
case R.id.nav_chat:
bottomNavigationView.setSelectedItemId(R.id.action_chat);
ft.replace(R.id.f_container, chatFragment);
break;
case R.id.nav_notifications:
bottomNavigationView.setSelectedItemId(R.id.action_notifications);
ft.replace(R.id.f_container, notificationFragment);
break;
}
ft.commit();
return true;
}
I have forked your repo and migrated it to AndroidX before fixing it on a new branch called androidx. I made a pull request to you. You can accept and try it.

try this code:
private void setupNavDrawer(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()){
case R.id.nav_gallery:
fragment = new GalleryFragment();
break;
case R.id.nav_share:
fragment = new ShareFragment();
break;
default:
fragment = new GalleryFragment();
break;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
//if checked - set title menu
item.setChecked(true);
setTitle(item.getTitle());
mDrawerLayout.closeDrawers();
return true;
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
............//nav
setupNavDrawer(navigationView);
}

Related

When I click the bottom navigation item more times the fragment loading again

This is my code I have created a bottom navigation view and I am connected the items to fragment separately. When I click the the navigation item more time the fragment load again again.
I don't know what is the problem here.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment SelectedFragment=null;
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.commit();
switch (item.getItemId()) {
case R.id.navigation_home:
setTitle("Playing11");
HomeFragment fragment = new HomeFragment();
ft.replace(R.id.fragment_container, fragment);
return true;
case R.id.navigation_dashboard:
HomeFragment1 fragment1 = new HomeFragment1();
ft.replace(R.id.fragment_container, fragment1);
return true;
case R.id.navigation_notifications:
setTitle("Safe11");
HomeFragment2 fragment2 = new HomeFragment2();
ft.replace(R.id.fragment_container, fragment2);
return true;
case R.id.navigation_notification:
setTitle("More");
HomeFragment3 fragment3 = new HomeFragment3();
ft.replace(R.id.fragment_container, fragment3);
return true;
}
return false;
}
};
}
Try to change your code like this:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (item.getItemId()) {
case R.id.menu_home:
HomeFragment homeFragment = new HomeFragment();
fragmentTransaction.replace(R.id.frameContentPlace, homeFragment, "HomeFragment").addToBackStack("HomeFragment");
break;
case R.id.menu_profile:
HomeFragment1 fragment1 = new HomeFragment1();
fragmentTransaction.replace(R.id.frameContentPlace, fragment1).addToBackStack("HomeFragment1");
break;
case R.id.menu_bookings:
HomeFragment2 fragment2 = new HomeFragment2();
fragmentTransaction.replace(R.id.frameContentPlace, fragment2).addToBackStack("HomeFragment2");
break;
}
fragmentTransaction.commit();
return true;
}
When you adding fragment use tag. So write
ft.replace(R.id.fragment_container, fragment, "MyFragment);
instead of
ft.replace(R.id.fragment_container, fragment);
And check if this fragment is visible for not loading this fragment again
switch (item.getItemId())
{
case R.id.navigation_home:
HomeFragment fragment = (HomeFragment)getFragmentManager().findFragmentByTag("MyFragment");
if (fragment != null && !fragment.isVisible())
{
setTitle("Playing11");
HomeFragment fragment = new HomeFragment();
ft.replace(R.id.fragment_container, fragment);
return true;
}
}

getting wrong fragment onclick of bottomnavigation

Hi i'm making an app where i'm using fragments with bottom navigation however when i click on home button it doesnt load home fragment instead it loads the second fragment and moreover when i start the app home fragment doesnt load by default i know it may sound naive but i'm having this problem plaese if someone may guide me
my code for fragment navigation
public class MainActivity extends AppCompatActivity {
FrameLayout frameLayout;
FragmentManager fragmentManager;
Fragment fragment;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//BottomNavigationView b=findViewById(R.id.bottom_nav);
fragmentManager = getSupportFragmentManager();
if(findViewById(R.id.frame_container)!=null){
if(savedInstanceState!=null){
return;
}
/*HomeFragment homeFragment = new HomeFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, homeFragment,null);
transaction.addToBackStack(null);
/* Comment this line and it should work!*/
//transaction.addToBackStack(null);
//transaction.commit();
}
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_nav);
//final SeekBar sb = (SeekBar) findViewById(R.id.sb);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()){
case R.id.navigation_home:
fragment = new HomeFragment();
loadFragment(fragment);
case R.id.navigation_feed:
fragment = new FeedFragment();
loadFragment(fragment);
return true;
case R.id.navigation_event:
fragment = new EventsFragment();
loadFragment(fragment);
return true;
case R.id.navigation_nearby:
fragment = new NearbyFragment();
loadFragment(fragment);
return true;
case R.id.navigation_profile:
fragment = new ProfileFragment();
loadFragment(fragment);
return true;
}
return false;
}
});
}
private void loadFragment(Fragment fragment) {
// HomeFragment homeFragment = new HomeFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment,null);
transaction.addToBackStack(null);
/* Comment this line and it should work!*/
//transaction.addToBackStack(null);
transaction.commit();
// load fragment
//HomeFragment homeFragment = new HomeFragment();
}
}
You just forgot to return true; inside case R.id.navigation_home: check it
Try this
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()){
case R.id.navigation_home:
fragment = new HomeFragment();
loadFragment(fragment);
return true;
case R.id.navigation_feed:
fragment = new FeedFragment();
loadFragment(fragment);
return true;
case R.id.navigation_event:
fragment = new EventsFragment();
loadFragment(fragment);
return true;
case R.id.navigation_nearby:
fragment = new NearbyFragment();
loadFragment(fragment);
return true;
case R.id.navigation_profile:
fragment = new ProfileFragment();
loadFragment(fragment);
return true;
}
return false;
}
});

How to implement default activity (fragment) on app load. (Drawer Layout)

I am using fragments and have successfully set up all the activities. Everything is fully functional.
My issue is that I can't seem to have a default layout or fragment class load when the app starts up initially.
I have tried a few methods with weird results. Here is my code from MainActivity.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
if (id == home) {
fragment = new Home();
} else if (id == services) {
fragment = new Services();
} else if (id == beforeAfter) {
fragment = new BeforeAfter();
} else if (id == staff) {
fragment = new Staff();
} else if (id == patientInfo) {
fragment = new Patient();
} else if (id == blog) {
fragment = new Blog();
} else if (id == contactUs) {
fragment = new Contact();
}
if (fragment != null) {
android.support.v4.app.FragmentManager fragmentManager =
getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.screen_area, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is my fragment code for Home.class
public class Home extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.home, null);
}
}
After editing my MainActivity java file and appending onCreate with
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.screen_area, new Home());
ft.commit();
It now works. I guess I was assigning the name of the XML layout page for Home fragment instead of the ID of the FrameLayout under content_main.
call the fragment in your onCreate
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new Fragment1());
ft.commit();
your code looks fine. I guess the problem is in your activity_main.xml
make sure you have only two childs inside the DrawerLayout
one for your main container and one the NavigationView
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/my_navigation_items" />
</android.support.v4.widget.DrawerLayout>
you need to show your fragments inside onCreate
FragmentTransaction mFragmentTransaction = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new YourFragment());
ft.commit(); //important

How to create a Image gallery inside a fragment in Android Studio

So I've created a Gallery Fragment in my navigation drawer. Now my question is, how do I create an image gallery once you clicked the "gallery" in my drawer step by step using gridView. Other tutorials in the internet uses MainActivity, which in my case, I need to put it in my GalleryFragment, but a fragment is in a whole new level. My codes are below.
for my MainActivity.java:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set the fragment initially
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
//-------------------------'
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
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 = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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 onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
//Set the fragment initially
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
// Handle the camera action
} else if (id == R.id.nav_gallery) {
GalleryFragment fragment = new GalleryFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_about) {
AboutFragment fragment = new AboutFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_contact) {
ContactFragment fragment = new ContactFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
GalleryFragment.java:
public class GalleryFragment extends Fragment {
public GalleryFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_gallery, container, false);
}
}
fragment_gallery.xml:
<RelativeLayout 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"
tools:context="com.example.guitarista.citem.GalleryFragment">
<!-- TODO: Update blank fragment layout
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
-->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GALLERY"
android:padding="8dp"
android:textColor="#fff"
android:background="#color/colorPrimary"
android:textSize="28sp"
android:id="#+id/main_button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

how to change Action bar icon to back arrow when open a fragment

I am trying to create an app. I want to change navigation drawer icon to back Arrow in Action Bar and when i open a fragment and go back to main activity when i click on back arrow in fragment Using the following code-
public class MainActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener,LocationListener{
DrawerLayout mDrawerLayout;
ListView mDrawerList;
#SuppressWarnings("deprecation")
ActionBarDrawerToggle mDrawerToggle;
String mTitle="";
private final String TAG = this.getClass().getSimpleName();
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
GoogleMap mMap;
SupportMapFragment mFragment;
Marker CurrentMarker,NearbyPlace,FindMarker;
EditText editplace = null;
Button findbtn = null;
boolean firstRun = true;
private Boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for connectivity service
ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cManager.getActiveNetworkInfo();
if (nInfo != null && nInfo.isConnected()) {
Toast.makeText(this, "Network is available ", Toast.LENGTH_SHORT).show();
AdView adView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice("abc")
.build();
adView.loadAd(adRequest);
mFragment=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
}
else{
Toast.makeText(this, "Network is not available ", Toast.LENGTH_SHORT).show();
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
newFragment = new NetworkCheck();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
editplace = (EditText) findViewById(R.id.editplace);
findbtn = (Button) findViewById(R.id.findbtn);
setListnerOnWidget();
mTitle = (String) getTitle();
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle( this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("Select a menu");
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drawer_list_item ,
getResources().getStringArray(R.array.menu)
);
mDrawerList.setAdapter(adapter);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
displayView(position);
// Updating the action bar title
String[] menu = getResources().getStringArray(R.array.menu);
mTitle = menu[position];
mDrawerLayout.closeDrawer(mDrawerList);
}
private void displayView(int position) {
// TODO Auto-generated method stub
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new Help();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 1:
newFragment = new ContactUs();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
transaction.addToBackStack(null);
getActionBar().setTitle("IQWINER");
try
{
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.iqwiner\n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "Choose an action"));
}
catch(Exception e)
{ //e.toString();
}
break;
case 3:
newFragment = new Suggestion_Address();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Log.e(TAG, "Suggestion Address button is clicked");
break;
}
}
});
}
private void setListnerOnWidget() {
// TODO Auto-generated method stub
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String location = editplace.getText().toString();
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
}
}
};
findbtn.setOnClickListener(listener);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
//for back button
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(Gravity.START)){
mDrawerLayout.closeDrawer(Gravity.START);
}
else if(getFragmentManager().getBackStackEntryCount() > 1){
super.onBackPressed();
}
else{
if (exit){
finish(); // finish activity
}
else{
Toast.makeText(this, "Tap Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
}
I want to change navigation drawer icon to back arrow icon when i open a fragment and when i click on back arrow then go back to main activity from a fragment.
Thanks
Remove the below code :
mDrawerToggle.setDrawerIndicatorEnabled(true);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drawer_list_item ,
getResources().getStringArray(R.array.menu)
);
mDrawerList.setAdapter(adapter);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
displayView(position);
// Updating the action bar title
String[] menu = getResources().getStringArray(R.array.menu);
mTitle = menu[position];
mDrawerLayout.closeDrawer(mDrawerList);
}
private void displayView(int position) {
// TODO Auto-generated method stub
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new Help();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 1:
newFragment = new ContactUs();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
transaction.addToBackStack(null);
getActionBar().setTitle("IQWINER");
try
{
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.iqwiner\n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "Choose an action"));
}
catch(Exception e)
{ //e.toString();
}
break;
case 3:
newFragment = new Suggestion_Address();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Log.e(TAG, "Suggestion Address button is clicked");
break;
}
}
});
and change it with below code:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.drawer_home:
txt_title.setText("Home");
Intent intent=new Intent(HomeActivity.this, HomeActivity.class);
startActivity(intent);
finish();
return true;
case R.id.drawer_artist:
txt_title.setText("Artists");
android.support.v4.app.FragmentManager fragmentManager=getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new ArtistsFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return true;
case R.id.drawer_myplaylist:
txt_title.setText("My Playlists");
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new PlayListFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return true;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
});
Edit
xml:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:elevation="4dp"
android:layout_height="fill_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<include
android:id="#+id/tool_bar"
layout="#layout/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/home">
//Your layout
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="#drawable/bg_all"
app:itemIconTint="#android:color/white"
app:itemTextColor="#android:color/white"
app:theme="#style/list_item_appearance"
app:menu="#menu/drawer_menu" >
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
getSupportFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager()
.getBackStackEntryCount() > 0) {
getSupportActionBar()
.setDisplayHomeAsUpEnabled(true); // show
// back button
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
// show hamburger
getSupportActionBar()
.setDisplayHomeAsUpEnabled(false);
mDrawerToggle.syncState();
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout
.openDrawer(GravityCompat.START);
}
});
}
}
});
Use the following after mDrawerLayout.setDrawerListener(mDrawerToggle);

Categories