Load all fragments at once (including fragments which are inside fragments) - java

So this is my main activity class
public class NewMainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
DrawerLayout drawerLayout;
NavigationView navigationView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_main_activity);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.purple_500));
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, new HomeFragment()).commit();
bottomNav.setOnNavigationItemSelectedListener(navListener);
//NewNav
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navView);
navigationView.bringToFront();
ActionBarDrawerToggle toggle=new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.mm_home);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_faq:
selectedFragment = new FAQFragment();
break;
case R.id.nav_price:
selectedFragment = new PriceMarketFragment();
break;
case R.id.nav_news:
selectedFragment = new NewsFragment();
break;
}
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
I have a frame layout in my mainactivity xml which i have given ID fragment_container.
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="#id/appBarLayout"
app:layout_constraintBottom_toTopOf="#id/navBottom"/>
In bottom navigation, I have 4 fragments, in which 3 fragments (Home, Price and News), I have tablayouts (more fragments within fragments).
When the mainactivity starts (the application starts) i want all of the parent fragments and child fragments to be loaded. and then i only need to navigate through them.
How can i do this please help.

Related

Map fragment is not hidden when switch between fragments Android Studio

I'm trying to switch between fragments using a bottom navigation. However, if I switch to other fragments from the map fragment, the map fragment is still in the background while other fragment is being shown on the front.
Please see my code here:
public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private Fragment messageFragment = new MessageFragment();
private Fragment mapFragment = new MapsFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(R.id.hostFragment, mapFragment, null).commit();
fragmentManager.beginTransaction().add(R.id.hostFragment, messageFragment, null).commit();
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
//bottomNavigationView.setSelectedItemId(R.id.mapsFragment);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.mapsFragment:
fragmentManager.beginTransaction().hide(messageFragment).show(mapFragment).commit();
break;
case R.id.messageFragment:
fragmentManager.beginTransaction().hide(mapFragment).show(messageFragment).commit();
break;
}
return true;
}
};
}
Your Problem
You are adding both fragments to the same container, R.id.hostFragment.
fragmentManager.beginTransaction().add(R.id.hostFragment, mapFragment, null).commit();
fragmentManager.beginTransaction().add(R.id.hostFragment, messageFragment, null).commit();
Per the documentation for hide and show, this means that you are hiding and then showing the same container.
A Solution
Use two different container views:
fragmentManager.beginTransaction().add(R.id.mapContainer, mapFragment, null).commit();
fragmentManager.beginTransaction().add(R.id.messageContainer, messageFragment, null).commit();
Another Solution
Use replace instead of hiding and showing.
fragmentManager.beginTransaction().add(R.id.hostFragment, mapFragment, null).commit();
// Don't add this in `onCreate`
// fragmentManager.beginTransaction().add(R.id.hostFragment, messageFragment, null).commit();
...
// Replace the fragment currently being displayed
switch (item.getItemId()) {
case R.id.mapsFragment:
fragmentManager.beginTransaction().replace(R.id.hostFragment, mapFragment).commit();
break;
case R.id.messageFragment:
fragmentManager.beginTransaction().replace(R.id.hostFragment, messageFragment).commit();
break;
}

Switching between fragments in drawer menu does nothing

I am really new to android and I am really frustrated with it. I want to switch between fragments in drawer menu. However, the screen stays the same. In the drawer it says that I am on a particular fragment but I see no change. I set a different background to differentiate between them.
I believe that fragment manager is deprecated based on what people are saying but I don't know how to change it with. Also the thin is I don't know which tutorials are out of date because I have very little knowledge about android development.
Fragment code:
public class ToolsFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tools, container,false);
}
}
Main activity code:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new CharacterFragment());
navigationView.setCheckedItem(R.id.nav_characters);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else{
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_characters:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new CharacterFragment());
break;
case R.id.nav_episodes:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new EpisodesFragment());
break;
case R.id.nav_tools:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new EpisodesFragment());
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You forgot to call commit()
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new CharacterFragment()).commit();

How to use onBackPress button in fragment on Android

In my application I have NavigationView and into this NavigationView I have set menu for open some fragments!
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="320dip"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#000"
android:fitsSystemWindows="true"
app:headerLayout="#layout/tester_drawer_header"
app:itemIconTint="#fff"
app:itemTextColor="#fff"
app:menu="#menu/tester_drawer_main"/>
I want when click on this menu open one fragment and I want when go to nested fragments and press onBack button open first fragment not open backStack fragments!
I write below codes, but after click on back button back fragments from backStack, but I want just open first fragment!
MyActivity codes:
public class TesterDashboardActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tester_dashboard);
loadFragment(new TesterTestListFragment(), userName);
}
#Override
public void onBackPressed() {
fragmentBackCount = getSupportFragmentManager().getBackStackEntryCount();
if (fragmentBackCount <= 1) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
//finishAffinity();
super.onBackPressed();
}
} else {
getSupportFragmentManager().popBackStack();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_home:
loadFragment(new TesterTestListFragment(), userName);
break;
case R.id.nav_billing:
loadFragment(new TesterFinanceFragment(), context.getString(R.string.menu_billing));
break;
case R.id.nav_edit_profile:
loadFragment(new TesterProfileFilterEditFragment(), context.getString(R.string.menu_edit_profile));
break;
case R.id.nav_bank:
loadFragment(new TesterShebaFragment(), context.getString(R.string.menu_bank));
break;
case R.id.nav_report:
loadFragment(new TesterReportsFragment(), context.getString(R.string.menu_report));
break;
case R.id.nav_setting:
loadFragment(new TesterSettingFragment(), context.getString(R.string.menu_setting));
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void loadFragment(Fragment fragment, String toolbarTitle) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.testerFragment, fragment,TAG_FRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
toolbar.setTitle(toolbarTitle);
}
How can I fix it?
In your code I found when the fragmentBackCount>1 you just call getSupportFragmentManager().popBackStack(); once, so you will see top fragment on backstack.
I think you should call getSupportFragmentManager().popBackStack();, fragmentBackCount-1 time to reach the first fragmnet
else {
for(int i=0;i<fragmentBackCount-1;i++)
getSupportFragmentManager().popBackStack();
}
When you are transitioning between Fragments, call addToBackStack() as part of your
FragmentTransaction:
FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace( R.id.fragment, new MyFragment() ).addToBackStack( "tag" ).commit();

Adding navigation drawer from second activity to activity_main. Using .opendrawer in main activity to open second

I have created a project int activity_main and want to add a Navigation drawer to it.
I have gone into the java folder. Right click > new > Actvity > Navigation Drawer activity.
Note: I DON't have an action bar, to create the menu button(3 stacked lines)
Now I don't know how to actually open the navigation drawer over activity_main, without the app crashing.
Thanks.
I've tried doing an on click listener with a button which has
the drawer layout defined as dl (DrawerLayout dl = (DrawerLayout)findviewbyIOd(R.id.Drawer_layout))
and have done
dl.openDrawer(Gravity.LEFT);
have tried putting the code from the NavDrawer activity into the activity_main, but app won't start.
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
Switch OnOff;
EditText editText;
int NumberPicked;
int NumberPicked2;
private DrawerLayout dl;
private ActionBarDrawerToggle abdt;
Values[] troughvals = new Values[8];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BobbleSelector BS = new BobbleSelector();
final DrawerLayout dl = (DrawerLayout)findViewById(R.id.dl);
Button btnChange = (Button) findViewById(R.id.btnChange);
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
btnChange.setOnClickListener( new View.OnClickListener(){
public void onClick(View v){
dl.openDrawer(Gravity.LEFT);
}
});
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return abdt.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
public void handleSwitchClick(View view) {
Switch s = (Switch) view;
boolean isChecked = s.isChecked();
}
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked){
switch (compoundButton.getId()){
case R.id.OnOff:
break;
}
}
}
Note: have disabled fab, because it could not be found in my project.
I have created a custom Menu for the Navigation Drawer
public class BobbleSelector extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bobble_selector);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Button fab = findViewById(R.id.btnChange);
// 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 = findViewById(R.id.dl);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.dl);
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.bobble_selector, 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();
DrawerLayout drawer = findViewById(R.id.dl);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Drawer 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/dl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_bobble_selector"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<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_bobble_selector"
app:menu="#menu/nav_menu" />
</android.support.v4.widget.DrawerLayout>
From Logcat
2019-06-02 13:13:08.195 12745-12745/com.example.mytest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mytest, PID: 12745
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.openDrawer(int)' on a null object reference
at com.example.mytest.MainActivity$1.onClick(MainActivity.java:49)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Expected to open drawer with the changebutton.openDrawer(Gravity.Left) But crashes the app.
Found I needed to move the code relating to the nav bar to the bottom of OnCreate and set the "SetContentView()" to be the layout for the Navigation bar.
Then it worked perfectly.
Before
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btnChange);
drawer = findViewById(R.id.dl);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer, R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//Not nav
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
//not nav
}
After
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btnChange);
//Not nav
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
//not nav
setContentView(R.layout.activity_bobble_selector);
drawer = findViewById(R.id.dl);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer, R.string.navigation_drawer_open,R.string.navigation_drawer_close);
assert drawer != null;
drawer.addDrawerListener(toggle);
toggle.syncState();
}

Android : Unable to integrate Drawer navigation because already calling extends for Google-Maps

I am working on an Android project in which I would like to add Drawer functionality, for which I already have classes and all ready.
THe problem is the Drawer code works by extends or extending the class which wants to add a drawer, and similarly my GoogleMaps code works in the same way. But because of Multiple-inheritance, I cannot extend 2 classes.
What should I do?
Google-maps code :
public class MapsActivity extends FragmentActivity {
GoogleMap googleMap;
SharedPreferences sharedPreferences;
int locationCount = 0;
private RestaurantServiceImpl restaurantService = new RestaurantServiceImpl();
List<RestRestaurant> restRestaurantList = new ArrayList<>();
GPSTracker gps;
double longitude, latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapsact);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Opening the sharedPreferences object
sharedPreferences = getSharedPreferences("location", 0);
// Getting number of locations already stored
locationCount = sharedPreferences.getInt("locationCount", 0);
// Getting stored zoom level if exists else return 0
String zoom = sharedPreferences.getString("zoom", "12");
gps = new GPSTracker(MapsActivity.this);
if (gps.canGetLocation()) {
longitude = gps.getLongitude();
latitude = gps.getLatitude();
restRestaurantList = this.restaurantService.getRestaurantsByLocation(longitude,latitude);
double lat=0, longi=0;
for(RestRestaurant restRestaurant : restRestaurantList){
drawMarker(new LatLng(restRestaurant.getLatitude(),restRestaurant.getLongitude()), restRestaurant.getRestaurantName(), restRestaurant.getRestaurantId());
lat = restRestaurant.getLatitude();
longi = restRestaurant.getLongitude();
}
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat,longi)));
// Setting the zoom level in the map on last position is clicked
googleMap.animateCamera(CameraUpdateFactory.zoomTo(Float.parseFloat(zoom)));
} else {
gps.showSettingsAlert();
}
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
int restoId = Integer.valueOf(marker.getSnippet());
Intent intent = new Intent(MapsActivity.this, MenuCardList.class);
intent.putExtra("restaurantid", restoId);
startActivity(intent);
finish();
return true;
}
});
}
This class I need to extend to add a drawer :
public class DrawerLoader extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
private ArrayList<DrawerModel> navDrawerItems;
private DrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawerlayout);
}
public void set(String[] navMenuTitles, TypedArray navMenuIcons) {
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<DrawerModel>();
If any more information is required, kindly let me know.
Ignoring all your work regarding a navigation drawer, this would be my preferred solution, since There is no need for a extra Fragment, List filling, new classes....
1, Create a nav_menu.xml (in menues folder):
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:checkableBehavior="single">
<item
android:id="#+id/drawer_home"
android:checked="true"
android:icon="#drawable/ic_home_black_24dp"
android:title="Home"/>
<item
android:id="#+id/drawer_favourite"
android:icon="#drawable/ic_favorite_black_24dp"
android:title="Favourites"/>
<item
android:id="#+id/drawer_settings"
android:icon="#drawable/ic_settings_black_24dp"
android:title="Settings"/>
</group>
2, Wrap your activites layout with a DrawerLayout:
<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">
<!-- Your activity layout here-->
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/nav_menu"/>
</android.support.v4.widget.DrawerLayout>
3, Update your activities java code:
//If you have a toolbar (recommended!)
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
//and finally the Navigation View Code:
final NavigationView navigation = (NavigationView) findViewById(R.id.navigation);
navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
navigation.setCheckedItem(menuItem.getItemId());
drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.drawer_home:
//open fragment home
return true;
case R.id.drawer_favourite:
//open fragment favourite
return true;
case R.id.nav_drawer_channels:
showFragment(2);
return true;
case R.id.drawer_settings:
//open settings
return true;
}
return false;
}
});
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
toolbar,
R.string.drawer_open, //simply a String "open"
R.string.drawer_close) { //simply a String "close"
public void onDrawerClosed(View view) {
super.onDrawerOpened(drawerLayout);
drawerToggle.syncState();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerClosed(drawerLayout);
drawerToggle.syncState();
}
};
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
//And, last but not least, open the drawer with a Click on 'home'
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
And you are done! No messing with extra fragment, unnecessary and messy code.

Categories