android navigation drawer fragment and ActionBarActivity - android

I have a navigation drawer and in one of the fragments, I'm trying to add a tab swipe layout. However I am unable to extend both ActionBarActivity and Fragment. Everything I've found online talks about FragmentActivity and not Fragment.
Is their a way to accomplish this?
This is my MainActivity :
public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch(position){
case 0:
objFragment = new myPantry_fragment();
break;
case 1:
objFragment = new myRecipes_fragment();
break;
case 2:
objFragment = new wheel_fragment();
break;
case 3:
objFragment = new addRecipes_fragment();//this causes errors
//when I change extends Fragment to extends ActionBarActivity
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4: //added this
mTitle = getString(R.string.title_section4);
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
This is my fragment I access from the navigation drawer.
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class addRecipes_fragment extends ActionBarActivity {
View rootview;
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
#Nullable
//#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.addrecipes_layout, container, false); //error shows in video too
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR); //
// setContentView(R.layout.activity_main);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager) rootview.findViewById(R.id.pager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getSupportActionBar();
actionBar.setSelectedNavigationItem(position);
}
});
Tab.setAdapter(TabAdapter);
actionBar = getSupportActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
Log.d("selected: ", "onTabSelected at" + "position" + tab.getPosition() + " " + tab.getText());
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
Log.d("Unselected: ", "onTabSelected at" + "position" + tab.getPosition() + " " + tab.getText());
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
Log.d("Reselected: ", "onTabSelected at" + "position" + tab.getPosition() + " " + tab.getText());
}
};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("General").setTabListener(tabListener)); //Android
actionBar.addTab(actionBar.newTab().setText("Add Ingredients").setTabListener(tabListener)); //IOS
actionBar.addTab(actionBar.newTab().setText("Add steps").setTabListener(tabListener)); //Windows
return rootview;
}
}

Keep your addRecipes_fragment extending the Fragment from support lib. Use a Viewpager in the Fragment layout to display the tabs and a custom PagerAdapter to load them using childfragment manager. Check this link.

Related

FragmentActivity error Android Studio

Hi i am creating an activity with 4 selection in drawerlayout. Once the user select, a fragment will appear.
First I use Fragment and it run but when I try to convert it into FragmentActivity, i got an error on this line -
fragmentManager.beginTransaction().replace(R.id.main_fragment_container,
fragment).commit();
private void selectItemFragment(int position){
FragmentActivity fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
switch(position) {
default:
case 0:
fragment = new FragmentDoctor();
break;
case 1:
fragment = new FragmentHospital();
break;
case 2:
fragment = new FragmentPharmacy();
break;
case 3:
fragment = new FragmentClinic();
break;
}
fragmentManager.beginTransaction().replace(R.id.main_fragment_container, fragment).commit();
FRAGMENT DOCTOR
public class FragmentDoctor extends FragmentActivity {
GoogleMap map;
public FragmentDoctor() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_doctor);
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null){
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (map != null){
setUpMap();
}
}
}
private void setUpMap() {
map.setMyLocationEnabled(true);
}
MAIN ACTIVITY
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
String[]titles = {"Doctor", "Hospital", "Pharmacy", "Specialty Clinic"};
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private ActionBarDrawerToggle mDrawerToggle;
private Toolbar topToolBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = " ";
topToolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
topToolBar.setLogo(R.drawable.logo);
topToolBar.setLogoDescription(" ");
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
LayoutInflater inflater = getLayoutInflater();
List<ItemObject> listViewItems = new ArrayList<ItemObject>();
listViewItems.add(new ItemObject("Doctor", R.drawable.icon_doctor));
listViewItems.add(new ItemObject("Hospital", R.drawable.icon_hospital));
listViewItems.add(new ItemObject("Pharmacy", R.drawable.icon_pharmacy));
listViewItems.add(new ItemObject("Specialty Clinic", R.drawable.icon_clinic));
//FIRST FRAGMENT AFTER SPLASH SCREEN
selectItemFragment(0);
mDrawerList.setAdapter(new CustomAdapter(this, listViewItems));
mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(null);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(null);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItemFragment(position);
}
});
}
private void selectItemFragment(int position){
Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
switch(position) {
default:
case 0:
fragment = new FragmentDoctor();
break;
case 1:
fragment = new FragmentHospital();
break;
case 2:
fragment = new FragmentPharmacy();
break;
case 3:
fragment = new FragmentClinic();
break;
}
fragmentManager.beginTransaction().replace(R.id.main_fragment_container, fragment).commit();
mDrawerList.setItemChecked(position, true);
setTitle(null);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(null);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
#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;
}
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
IMPORTS IN MAIN ACTIVITY
android.content.res.Configuration;
android.support.v4.app.Fragment;
android.support.v4.app.FragmentManager;
android.support.v4.widget.DrawerLayout;
android.support.v7.app.ActionBarActivity;
android.support.v7.app.ActionBarDrawerToggle;
android.os.Bundle;
android.support.v7.widget.Toolbar;
android.view.LayoutInflater;
android.view.Menu;
android.view.MenuItem;
android.view.View;
android.widget.ListView;
FragmentDoctor should extend from Fragment not from FragmentActivity
change this code
public class FragmentDoctor extends FragmentActivity {
like this
public class FragmentDoctor extends Fragment {
and
private void selectItemFragment(int position){
FragmentActivity fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
switch(position) {
default:
case 0:
fragment = new FragmentDoctor();
break;
case 1:
fragment = new FragmentHospital();
break;
case 2:
fragment = new FragmentPharmacy();
break;
case 3:
fragment = new FragmentClinic();
break;
}
if(fragment != null) {
fragmentManager.beginTransaction().
replace(R.id.main_fragment_container, fragment).commit();
}
As below
import android.support.v4.app.FragmentActivity;
FragmentActivity is part of support-v4 library..
So please add below dependency to your gradle file :
compile 'com.android.support:support-v4:23.0.1'
You can also add this library by following below steps in Android Studio :
Select File
Select Project Structure
Select app
Select dependencies
Click on '+'
Select library dependency
Select support v4 library and
Press 'OK'
Edited :
public class FragmentDoctor extends FragmentActivity {
And also From your edited code I have noticed that you are extending FragmentActivity not Fragment.
So please follow below link for more information on How to create Fragment with FragmentActivity :
http://www.codepuppet.com/2013/10/06/using-fragments-in-android-with-fragmentactivity/
Thanks

Android - Adding side navigator from template

I have an existing app to which I would like to add a side navigator.
I realized that Android SDK provides a template for that (by adding side navigation drawer activity from the Add menu) but not sure about how to add it the app.
Here is the code of the sidebar class was generated:
package com.testapp;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
public class SideNavActivity extends Activity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_side_nav);
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.side_nav, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_side_nav,
container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((SideNavActivity) activity).onSectionAttached(getArguments()
.getInt(ARG_SECTION_NUMBER));
}
}
}
and here is the code of one of the activities I have:
public class MainMenu extends SideNavActivity implements IResponsable{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main_menu);
final Button btnLogout = (Button) findViewById(R.id.btn_logout);
final Button btnProfile= (Button) findViewById(R.id.btn_prfile);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new HttpGet(HttpClient.getClient(), MainMenu.this).execute("auth/logout");
}
});
btnProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent prof = new Intent(MainMenu.this, ProfileActivity.class);
startActivity(prof);
//finish();
}
});
}
#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, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void getResponse(Object iResult) {
int code = Utils.ParseResponse.getResponseCode((Response)iResult);
if(code == 200)
{
SaveSharedPreference.clearUserName(getApplicationContext());
Intent menu = new Intent(MainMenu.this, LoginActivity.class);
startActivity(menu);
finish();
}
else if(code == 403){
SaveSharedPreference.clearUserName(getApplicationContext());
Intent menu = new Intent(MainMenu.this, LoginActivity.class);
menu.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(menu);
finish();
}
}
}
It also generated simple valid xml files.
When adding this activity in a new blank project, it works fine.
Thank you so much for the assistance!!
With introduction of Android Design Library, the navigation drawer has been reworked and here you will find awesome explanation how now it works:
http://android-developers.blogspot.com/2015/05/android-design-support-library.html
Also there is a sample project created by guys from Google:
https://github.com/chrisbanes/cheesesquare
Take a look at setupDrawerContent method here:
https://github.com/chrisbanes/cheesesquare/blob/master/app/src/main/java/com/support/android/designlibdemo/MainActivity.java#L111
and relevant layout file here:
https://github.com/chrisbanes/cheesesquare/blob/master/app/src/main/res/layout/activity_main.xml

Passing data from one fragment to another is not working when passing data

I have a fragment fragmentA on which I have a gridview. The user clicks on a row the grid, I read the value of the first column and pass it to another fragment MapFragment. When I run in debug mode, I can see that the data from fragmentA is passed to the main activity and the app crashes.
What is wrong with code? Am I missing anything?
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.text.MainActivity.SendData(MainActivity.java:51)
at com.test.fragmentAFragment$1.onItemClick(BurnScheduleFragment.java:50)
at android.widget.AdapterView.performItemClick(AdapterView.java:301)
at android.widget.AbsListView.performItemClick(AbsListView.java:1539)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3332)
at android.widget.AbsListView$1.run(AbsListView.java:4554)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
I have an interface as
`public interface Communicate {
public void SendData(String place);
}
In MapFragment
public class MapFragment extends Fragment {
private MapView map;
HashMap markerMap = new HashMap();
Marker marker;
public MapFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
}
public void Show(String title)
{
Marker showMarkerOnMap = (Marker)markerMap.get(title);
showMarkerOnMap.showInfoWindow();
}
private void CreateMarkers(){
GoogleMap gMap = map.getMap();
gMap.setMyLocationEnabled(true);
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
marker = gMap.addMarker(new MarkerOptions().title("One")
.snippet("description")
.position(new LatLng( 0, 0)));
markerMap.put("One", marker);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getApplicationContext()) == ConnectionResult.SUCCESS) {
//Initialze mapview
MapsInitializer.initialize(getActivity());
map = (MapView) view.findViewById(R.id.mapView);
map.onCreate(savedInstanceState);
CreateMarkers();
} else {
Toast.makeText(getActivity(), "Please install google play services", Toast.LENGTH_LONG).show();
}
return view;
}
#Override
public void onResume() {
super.onResume();
map.onResume();
}
#Override
public void onPause() {
super.onPause();
map.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
map.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
map.onLowMemory();
}
}
In My MainAcyivity I have
implemented the SendData as
public void SendData(String place)
{
FragmentManager fragmentManager = getSupportFragmentManager();
MapFragment mapFragment = (MapFragment)fragmentManager.findFragmentById(R.id.mapView);
mapFragment.Show(place);
}
and I have added the method Show in the MapFragment
public void Show(String title)
{
Marker showMarkerOnMap = (Marker)markerMap.get(title);
showMarkerOnMap.showInfoWindow();
}
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks, Communicate {
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
public void SendData(String place)
{
FragmentManager fragmentManager = getSupportFragmentManager();
MapFragment mapFragment = (MapFragment)fragmentManager.findFragmentById(R.id.mapView);
mapFragment.Show(place);
}
#Override
public void onNavigationDrawerItemSelected(int position)
{
// update the main content by replacing fragments
Fragment fragment = null;
switch (position){
case 0:
fragment= new MapFragment();
break;
case 1:
fragment = new BFragment();
break;
case 2:
break;
default:
fragment = new AFragment();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
`
Map_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
Your fragment is null. Otherwise the NullPointerException would be caused by the Fragment and not the Activity. Did you call getFragmentById with the correct ID which is the container ID or the XML-ID?
To pass value from activity to fragment or fragment to fragment, use setArgument.
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
How to pass values between Fragments
I hope it will help for you.

How to Call Navigation Drawer Fragment from Activity?

I have a Navigation Drawer which is created by Android studio. I Called a Activity from the Navigation Drawer.In that Activity, the navigation drawer is not showing up ?
How can i Call the Navigation Drawer from the below Activity ?
PlayerActivity
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
public class PlayerActivity extends Activity {
private static final int REQ_START_STANDALONE_PLAYER = 1;
private static final int REQ_RESOLVE_SERVICE_MISSING = 2;
private static final String PLAYLIST_ID = "PL5BxbbBpI7r";
public static final String DEVELOPER_KEY = "AIwXEZQLS-U";
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
}
public void Play(View v) {
int startIndex = 0;
int startTimeMillis = 0;
boolean autoplay = true;
boolean lightboxMode = false;
Intent intent = null;
intent = YouTubeStandalonePlayer.createPlaylistIntent(this, DEVELOPER_KEY,
PLAYLIST_ID, startIndex, startTimeMillis, autoplay, lightboxMode);
if (intent != null) {
if (canResolveIntent(intent)) {
startActivityForResult(intent, REQ_START_STANDALONE_PLAYER);
} else {
// Could not resolve the intent - must need to install or update the YouTube API service.
YouTubeInitializationResult.SERVICE_MISSING
.getErrorDialog(this, REQ_RESOLVE_SERVICE_MISSING).show();
}
}
}
private boolean canResolveIntent(Intent intent) {
List<ResolveInfo> resolveInfo = getPackageManager().queryIntentActivities(intent, 0);
return resolveInfo != null && !resolveInfo.isEmpty();
}
}
Navigation.java
public class Navigation extends Activity
implements HomeFragment.OnFragmentInteractionListener, NavigationDrawerFragment.NavigationDrawerCallbacks, NewsFragment.OnFragmentInteractionListener{
#Override
public void onFragmentInteraction(Uri uri) {
}
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mNavigationDrawerFragment = (NavigationDrawerFragment)getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
switch(position){
case 0:
HomeFragment homeFragment = new HomeFragment();
fragmentManager.beginTransaction().replace(R.id.container, HomeFragment.newInstance("",""))
.commit();
break;
case 1:
NewsFragment newsFragment = new NewsFragment();
fragmentManager.beginTransaction()
.replace(R.id.container, NewsFragment.newInstance("",""))
.commit();
break;
case 2:
Intent intent= new Intent(this,PlayerActivity.class);
startActivity(intent);
break;
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.navigation, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_navigation, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((Navigation) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
NavigationDrawer is meant to work with fragments, because the drawer is a fragment itself. You can access that drawer as long as you stay in the same Activity but once you change Activity you can't access to the drawer (Unless you create another instance of the drawer, but then you are missing the whole point of it). In order to accomplish what you want I'd recommend two things.
1) Instead of launching a new Activity make PlayerActivity a fragment.
2) Create a BaseActivity with a drawer and make all your other Activities extend it, that way you only have one single reference to the drawer in your project.
You should use fragment instead of activity! You should have two fragments as default when you create the project. One is for navigation drawer, and the other one is for content. You should replace that content fragment with your new content which you put in second activity..
You need to do the same thing in the PlayerActivity
mNavigationDrawerFragment = (NavigationDrawerFragment)getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
Also put navigation drawer inside R.layout.activity_player.
Like you did in R.layout.activity_navigation

How to get items in Navigation Drawer to change view

I want to make an simple app with a Navigation Drawer, which can open other views (News, Information, Gallery, Contact etc). So I opened up the latest Android Studio, made a new project that is compatible with API8>API19, to get maximum reach.
I chose the preset Navigation Drawer and clicked finish. I have figured out to change the names of the items in the Navigation Drawer, but how do I get these items to redirect to a new view?
I have tried implementing the setOnItemClickListener into the MainActivity as the Navigation Drawer site says on http://developer.android.com. But I can't seem to figure out how it all ties together, and it wont work.
tl;dr: I need help with making the items in the Navigation Drawer launch a new view/fragment, and probably an explanation on how it all works.
Here is the app project (Android Studio) https://www.dropbox.com/s/qfz9oul62dzt3rr/NTI_SHOWCASE.zip
MainActivity.java
package com.christianarne.ntishowcase;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private static final int SETTINGS_RESULT = 1;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.rgb(0, 153, 204))); // set your desired color
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
if (id == R.id.action_example) {
Intent intent_g = new Intent(this, Guide.class);
startActivity(intent_g);
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
Would it be better and easier to create an app with the Navigation Drawer from scratch, rather than using a pre-built?
Help is much appreciated.
Well, I'll left this here in case someone needs help switching Fragments in an "Android Studio" Navigation Drawer project
The answer proposed by user2511882, uses the following:
fragment = new FirstFragment();
But the code generated by "Android Studio" uses:
fragment = FirstFragment.newInstance();
(which is a better practice; see why HERE)
That's why his answer doesn't work for your project.
In your case, you have to use something like:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = FirstFragment.newInstance(position + 1);
break;
case 1:
fragment = SecondFragment.newInstance(position + 1);
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
In "Android Studio" it is also a good practice to read the comments and "TODOS" incorporated in the auto generated code.
best regards.
You will need to setup a setOnItemClickListener on your drawerLayout(the id of the listview in your xml file)
Example:
drawerLayout.setOnItemClickListener(new ListView.onItemClickListener){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
displayView(position);
}}
private void displayView(int position) {
switch (position) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_layout_id, fragment).commit(); //
And you need to make separate java class for the FirstFragment and SecondFragment with whatever content you need.
get Item position in navigation view you can set first 0th position menu default by
navigationView.getMenu().getItem(0); // default selected menu
displayview(navigationView.getMenu().getItem(0));
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
displayView(menuItem);
return true;
}
});
}
public void displayView(MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_home:
// fragment = new CheeseListFragment();
break;
case R.id.nav_messages:
fragment = new MessageFragment();
break;
}
if(fragment != null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, fragment)
.commit();
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
}
}
get Item position in navigation view you can set first 0th position menu default by
navigationView.getMenu().getItem(0); // default selected menu

Categories

Resources