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
Related
I've been searching and thinking how to implement the desire behaviour that I want when switching back and forth between fragments when using a Navigation Drawer. Actually the documentation says:
When using fragments in your app, individual FragmentTransaction objects may represent context changes that should be added to the back stack. For example, if you are implementing a master/detail flow on a handset by swapping out fragments, you should ensure that pressing the Back button on a detail screen returns the user to the master screen
So in my app I have a MainActivity that controls everything and a navigation layout within you can change between predefined options. This is the view when you launch the app
When you click on an item in the navigation drawer it opens a new fragment that replaces the main_content as follows:
At this point the behaviour is the correct one, so if you want to change the options you need to open the navigation drawer again to toggle between the menu options.
This is the Main Activity (notice that there is no Drawer Toggle)
MainActivity.java
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout drawerLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSnackBarView = findViewById(R.id.myCoordinatorLayout);
setToolbar(); // Set Toolbar como action bar
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
drawerTitle = getResources().getString(R.string.app_name);
if (savedInstanceState == null) {
selectItem(drawerTitle, mCurrentSelectedPosition);
}
}
private void setToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
if (ab != null) {
// Poner ícono del drawer toggle
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Marcar item presionado
menuItem.setChecked(true);
// Crear nuevo fragmento
String title = menuItem.getTitle().toString();
int id = menuItem.getItemId();
selectItem(title, id);
return true;
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectItem(String title, int id) {
Bundle args = new Bundle();
args.putString(PlaceholderFragment.ARG_SECTION_TITLE, title);
Fragment fragment = PlaceholderFragment.newInstance(title);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
switch (id) {
case R.id.nav_localizacion:
//Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 0;
LocalizacionFragment fragment_localizacion = new LocalizacionFragment();
// fragmentManager = getSupportFragmentManager();
Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_localizacion)
.commit();
break;
case R.id.nav_productos:
Snackbar.make(mSnackBarView, R.string.menu_productos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 1;
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
break;
case R.id.nav_consejos:
Snackbar.make(mSnackBarView, R.string.menu_consejos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 3;
ConsejosFragment fragment_consejo = new ConsejosFragment();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_consejo)
.commit();
break;
default:
break;
}
drawerLayout.closeDrawers(); // Cerrar drawer
setTitle(title); // título actual
}
}
I don't use the hamburger icon because it hides under the Navigation Layout, but here is the thing. When you click on "Recetas" in the recycle view it open a new fragment (replace) but now I want to show the up caret icon and give proper back navigation to my app.
Here is the code of the "Consejos" fragment class
Consejos.java
public class ConsejosFragment extends Fragment {
RecyclerView mRecycler;
ConsejosAdapter mAdapter;
FragmentActivity mActivity;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = (FragmentActivity) activity;
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
List items = new ArrayList();
items.add(new ConsejosInfo("Recetas", R.drawable.icon_recetas));
/* Inflamos el layout */
View v = inflater.inflate(R.layout.consejos_layout_recycler, container, false);
/* Obtenemos el Recycle */
mRecycler = (RecyclerView) v.findViewById(R.id.recycler_consejos);
/* Creamos el adaptador */
mAdapter = new ConsejosAdapter(mActivity, items);
/* Set click en adapter */
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecycler.setHasFixedSize(true);
mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecycler.setAdapter(mAdapter);
}
}
And this is the adapter that the Recyclerview use and handles the click on the item inside:
Adapter.java
public class ConsejosAdapter extends RecyclerView.Adapter<ConsejosAdapter.ConsejosViewHolder> {
private List<ConsejosInfo> _items = new ArrayList<ConsejosInfo>();
private final FragmentActivity mActivity;
private Context context;
public ConsejosAdapter(FragmentActivity mActivity, List<ConsejosInfo> items) {
this._items = items;
this.mActivity = mActivity;
}
#Override
public int getItemCount() {
return _items.size();
}
#Override
public ConsejosViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardview_consejos, viewGroup, false);
return new ConsejosViewHolder(v);
}
#Override
public void onBindViewHolder(ConsejosViewHolder viewHolder, int position) {
viewHolder.imagen.setImageResource(_items.get(position).get_imagen());
viewHolder.nombre.setText(_items.get(position).get_nombre());
}
public class ConsejosViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView imagen;
public TextView nombre;
public ConsejosViewHolder(final View itemView) {
super(itemView);
imagen = (ImageView) itemView.findViewById(R.id.consejos_imagen);
nombre = (TextView) itemView.findViewById(R.id.consejos_nombre);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
RecetasFragment recetasFragment = new RecetasFragment();
FragmentManager fragmentManager = mActivity.getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, recetasFragment)
.addToBackStack(null)
.commit();
}
}
}
In the Consejos Adapter I added to backstack the fragment before calling the new fragment (inside fragment) and that changes the behaviour of the back button, so before this if you press the back button is closes the app but now it takes you to the Consejos fragment, but now I want to add the up caret and make the exactly same operation as when you click the back button but I don't know how to achieve it.
Please feel free to ask for more code
Thank you very much
I will give you the full answer:
We will use the interfaces to communicate with the MainActivity from RecetasFragment so we can enable and disable navigation back button.
RecetasFragment class:
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by hema on 8/19/2015.
*/
public class RecetasFragment extends Fragment {
private CommunicateWithActivity mWithActivity;
public RecetasFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mWithActivity = (CommunicateWithActivity) activity; // MainActivity must implement CommunicateWithActivity interface.
mWithActivity.enableNavigationBack(true); // We enable navigation back here.
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement CommunicateWithActivity");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recetas, container, false);
}
#Override
public void onDestroy() {
super.onDestroy();
mWithActivity.enableNavigationBack(false); // We disable navigation back here, restore menu icon.
}
public interface CommunicateWithActivity {
void enableNavigationBack(boolean enable);// we will implement this method in MainActivity class.
}
}
And in MainActivity class we will implement CommunicateWithActivity interface, Modify your MainActivity class (only required modifications):
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity implements RecetasFragment.CommunicateWithActivity {
private Toolbar mToolbar;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mToolbar.setNavigationIcon(R.drawable.ic_menu);
mSnackBarView = findViewById(R.id.myCoordinatorLayout);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
drawerTitle = getResources().getString(R.string.app_name);
if (savedInstanceState == null) {
selectItem(drawerTitle, mCurrentSelectedPosition);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Marcar item presionado
menuItem.setChecked(true);
// Crear nuevo fragmento
String title = menuItem.getTitle().toString();
int id = menuItem.getItemId();
selectItem(title, id);
return true;
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectItem(String title, int id) {
Bundle args = new Bundle();
args.putString(PlaceholderFragment.ARG_SECTION_TITLE, title);
Fragment fragment = PlaceholderFragment.newInstance(title);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
switch (id) {
case R.id.nav_localizacion:
//Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 0;
LocalizacionFragment fragment_localizacion = new LocalizacionFragment();
// fragmentManager = getSupportFragmentManager();
Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_localizacion)
.commit();
break;
case R.id.nav_productos:
Snackbar.make(mSnackBarView, R.string.menu_productos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 1;
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
break;
case R.id.nav_consejos:
Snackbar.make(mSnackBarView, R.string.menu_consejos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 3;
ConsejosFragment fragment_consejo = new ConsejosFragment();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_consejo)
.commit();
break;
default:
break;
}
drawerLayout.closeDrawers(); // Cerrar drawer
setTitle(title); // título actual
}
#Override
public void enableNavigationBack(boolean enable) {
if(enable) {
// We enable the navigation back button here
mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// On navigation back button clicked.
if(getSupportFragmentManager().getBackStackEntryCount() > 0) { // Check if there is fragments in BackStack.
getSupportFragmentManager().popBackStack(); // PopBackStack.
} else {
// You can implement this part as you want.
return;
}
}
});
} else {
mToolbar.setNavigationIcon(R.drawable.ic_menu);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(drawerLayout != null) {
drawerLayout.openDrawer(Gravity.LEFT);
}
}
});
}
}
}
Please let me know if there is something you don't understand.
So I've been basing my navigation drawer after code i found in a tutorial. However my fragments don't switch. Laptop is down and using AIDE. Anyone tell me what's wrong? Guessing it's my setonitemclicklistener.
{
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems()
{
String[] osArray = { "Hello", "Watch Ads", "TapJoy" };
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
selectView(position);
}
});
}
private void selectView(int position)
{
Fragment fragment = null;
switch (position)
{
case 0:
fragment = new HelloFragment();
break;
case 1 :
fragment = new AdFragment();
break;
case 2:
fragment = new TapJoyFragment();
break;
}
if (fragment == null)
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
} }
private void setupDrawer()
{
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("How will you earn?");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view)
{
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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 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;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
Hello dude !
private void selectView(int position)
{
Fragment fragment = null;
switch (position)
{
case 0:
fragment = new HelloFragment();
break;
case 1 :
fragment = new AdFragment();
break;
case 2:
fragment = new TapJoyFragment();
break;
}
**if (fragment == null)**
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
} }
This "if" statement alway be false How can fragment be null if u wrap it just before in switch(position). Thats why your fragment transaction will never come true.
Firstly take FragmentActivity instead of Activity...
private void selectView(int position)
{
Fragment fragment = null;
switch (position)
{
case 0:
fragment = new HelloFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,fragment).commit();
break;
case 1 :
fragment = new AdFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,fragment).commit();
break;
case 2:
fragment = new TapJoyFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,fragment).commit();
break;
}
Please use if(fragment != null) instead of (fragment == null).
Please I have a problem, in my code like its nothing wrong, why when I select content on Sliding Menu, Sliding menus are not automatically covered? What's wrong with my code? I do not use a fragment only uses a switch to display the menu
MainActivity.java
public class MainActivity extends FragmentActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mDrawerItems = getResources().getStringArray(R.array.list);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer oepns
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// Add items to the ListView
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mDrawerItems));
// Set the OnItemClickListener so something happens when a
// user clicks on an item.
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Set the default content area to item 0
// when the app opens for the first time
if(savedInstanceState == null) {
navigateTo(0);
}
}
/*
* If you do not have any menus, you still need this function
* in order to open or close the NavigationDrawer when the user
* clicking the ActionBar app icon.
*/
#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 super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
Intent i = new Intent(MainActivity.this, tentang.class);
startActivity(i);
}
if(mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/*
* When using the ActionBarDrawerToggle, you must call it during onPostCreate()
* and onConfigurationChanged()
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private class DrawerItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.v(TAG, "ponies");
navigateTo(position);
}
}
private void navigateTo(int position) {
Log.v(TAG, "List View Item: " + position);
switch(position) {
case 0:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
sejarah.newInstance(),
sejarah.sejarah).commit();
break;
case 1:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
pakaian.newInstance(),
pakaian.pakaian).commit();
break;
case 2:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
rumah.newInstance(),
rumah.rumah).commit();
break;
case 3:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
senjata.newInstance(),
senjata.senjata).commit();
break;
case 4:
Intent i = new Intent(MainActivity.this, lagu.class);
startActivity(i);
break;
case 5:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
musik.newInstance(),
musik.musik).commit();
break;
case 6:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
kesenian.newInstance(),
kesenian.kesenian).commit();
break;
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
}
you miss the the part drawer.closeDrawer(mDrawerList) or mDrawerLayout.closeDrawer(mDrawerList)
I created an app with Navigation Drawer in BaseActivity. Everything works ok except the change of title in the Action Bar. the title changes for a second but when opening the new activity is shown the original title.
What can be the error? thanks
BaseActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PerfilAdapter.iniciarBaseDatos(this);
perfilObj = PerfilAdapter.selectPerfil(1);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
cargarActionBar();
cargarDrawerLayout(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.menuOpcSonidos:
...
return true;
case R.id.menuOpcCambiarColor:
...
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.menuOpcSonidos)
.setTitle(getResources().getString(R.string.sonidoOnOff) + " " + perfilObj.getSonidos());
return super.onPrepareOptionsMenu(menu);
}
private void cargarActionBar() {
ActionBar actionBar = getActionBar();
int[] colores2 = Modulo.cargarColoresDrawerlayout(perfilObj.getColor());
actionBar.setBackgroundDrawable(new GradientDrawable(Orientation.BOTTOM_TOP, colores2));
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
int titleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
TextView textoTitulo = (TextView)findViewById(titleId);
textoTitulo.setTextColor(getResources().getColor(R.color.blanco));
textoTitulo.setTypeface(null, Typeface.BOLD);
textoTitulo.setTextSize(19);
textoTitulo.setShadowLayer(5, 0, 0, getResources().getColor(R.color.negro));
}
private void cargarDrawerLayout(Bundle b) {
mTitle = mDrawerTitle = getTitle();
textosMenuLateral = getResources().getStringArray(R.array.nav_drawer_items);
iconosMenuLateral1 = getResources()
.obtainTypedArray(R.array.iconos_menu_lateral1);
iconosMenuLateral2 = getResources()
.obtainTypedArray(R.array.iconos_menu_lateral2);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenuMain);
int[] colores = {0, 0xFFFFFFFF, 0};
mDrawerList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colores));
mDrawerList.setDividerHeight(4);
navDrawerItems1 = new ArrayList<DrawerItem>();
navDrawerItems1.add(new DrawerItem(textosMenuLateral[0], iconosMenuLateral1.getResourceId(0, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[1], iconosMenuLateral1.getResourceId(1, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[2], iconosMenuLateral1.getResourceId(2, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[3], iconosMenuLateral1.getResourceId(3, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[4], iconosMenuLateral1.getResourceId(4, -1)));
navDrawerItems2 = new ArrayList<DrawerItem>();
navDrawerItems2.add(new DrawerItem(textosMenuLateral[0], iconosMenuLateral2.getResourceId(0, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[1], iconosMenuLateral2.getResourceId(1, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[2], iconosMenuLateral2.getResourceId(2, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[3], iconosMenuLateral2.getResourceId(3, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[4], iconosMenuLateral2.getResourceId(4, -1)));
iconosMenuLateral1.recycle();
iconosMenuLateral2.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
adapter = new DrawerListAdapter(getApplicationContext(),
navDrawerItems1,
navDrawerItems2,
perfilObj.getColor(),
pos);
mDrawerList.setAdapter(adapter);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.icono_drawer,
R.string.app_name,
R.string.app_name
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (b == null) {
opcionesPanelLateral(0);
}
}
private class SlideMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView textView = (TextView) view.findViewById(R.id.title);
textView.setTypeface(null, Typeface.BOLD);
opcionesPanelLateral(position);
}
}
private void opcionesPanelLateral(int position) {
Intent i;
switch (position) {
case 0:
pos = 0;
break;
case 1:
i = new Intent(this, ActivitySecond.class);
mDrawerLayout.closeDrawer(mDrawerList);
startActivity(i);
pos = 1;
break;
case 2:
i = new Intent(this, ActivityThird.class);
mDrawerLayout.closeDrawer(mDrawerList);
startActivity(i);
pos = 2;
break;
case 3:
i = new Intent(this, ActivityFourth.class);
mDrawerLayout.closeDrawer(mDrawerList);
startActivity(i);
pos = 3;
break;
case 4:
break;
default:
break;
}
mDrawerList.setItemChecked(pos, true);
mDrawerList.setSelection(pos);
setTitle(textosMenuLateral[pos]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
cargarActionBar();
cargarDrawerLayout(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void onBackPressed() {
mDrawerLayout.closeDrawer(mDrawerList);
}
I think that error is the use the Activities... but I don't know as fix
Android Studio allows to add a navigation drawer to the app through File | New | Activity. This "ready-made" navigation drawer comes with everything you need: properties, methods, events, etc.
Next steps to change titles for different fragments are intended to use with the ready-made navigation drawer of Android Studio, but they might be helpful to anyothers:
The navigation drawer has several files : one activity, and one or
more fragments. Open the java activity file of your navigation drawer (what
you call "Base Activity").
Find method onCreate.
In this method, add the line mTitle = "???", where "???" is the title of
the first fragment that will me shown as soon as the navigation drawer
screen appears.
Now find method onNavigationDrawerItemSelected. CHARLIE, I'm not sure,
but I believe you have it under the name opcionesPanelLateral.
In this method you have a switch. This switch opens the appropiate
fragment depending on the selected option. To set the title for each
fragment, go to each case in the switch an add the line mTitle = "My
title"; before frg = new my_frag();. This way, when the fragment opens
it will show the appropiate title.
Find method restoreActionBar. CHARLIE, I don't see it in your code
nor any equivalent method. Add it. Inside of it, add the line
actionBar.setTitle( mTitle);, and here is where the title is actually
set (maybe that's why your title disappears). Call this method inside
onCreateOptionsMenu (after inflate).
That's it. I'm using hard-coded strings, if you follow Android rules, use strings.xml.
Now a real life example from and app I'm working on right now. Next is the raw code of my "BaseActivity" of the ready-made navigation drawer (some things are in spanish because I'm costarrican):
package my_package;
//------------------------------------------------------------------------------
import android.app.Activity;
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.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 menu_act extends ActionBarActivity
implements drawer_frg.NavigationDrawerCallbacks {
//------------------------------------------------------------------------------
// Fragment managing the behaviors, interactions and presentation of the navigation drawer.
private drawer_frg 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.menu_lay );
mNavigationDrawerFragment = (drawer_frg) getSupportFragmentManager().findFragmentById(
R.id.navigation_drawer );
mTitle = "Perfil"; // getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp( R.id.navigation_drawer,( DrawerLayout )
findViewById( R.id.drawer_layout ) );
// BARRA DE TÍTULO ANARANJADA.
//ActionBar actionBar = getSupportActionBar();
//actionBar.setBackgroundDrawable( new ColorDrawable( getResources().getColor( R.color.col_nar ) ) );
}
//------------------------------------------------------------------------------
#Override
public void onNavigationDrawerItemSelected ( int position ) {
Fragment frg;
// getSupportActionBar().setDisplayOptions( ActionBar.DISPLAY_SHOW_CUSTOM );
switch ( position )
{ case 0 : //getSupportActionBar().setCustomView( R.layout.perfil_tit );
mTitle = "Perfil";
frg = new perfil_frg();
break;
case 1 : // getSupportActionBar().setCustomView( R.layout.contactos_tit );
mTitle = "Contactos";
frg = new contactos_frg();
break;
default : frg = PlaceholderFragment.newInstance( position + 1 );
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace( R.id.container,frg ).commit();
}
//------------------------------------------------------------------------------
public void onSectionAttached ( int number ) {
switch (number) {
case 1 : mTitle = getString( R.string.mnu_opc_per ); break;
case 2 : mTitle = getString( R.string.mnu_opc_con ); break;
case 3 : mTitle = getString( R.string.mnu_opc_sal ); 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.menu_act,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;
*/
//mDrawerToggle.syncState();
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.menu_frg, container, false);
return rootView;
}
//------------------------------------------------------------------------------
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((menu_act) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER));
}
//==============================================================================
}
//------------------------------------------------------------------------------
}
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