Controlling which fragment is shown from navDrawer - android

I am working on this application that has a viewPager and a few swipeable fragments in its MainActivity. Today I implemented navigation drawer but I do not know how to control which fragment is shown from drawer`s DrawerItemClickListener class. Is there a solution or I was just moving in a wrong direction and have to change the way navigation drawer is implemented?
Tutorial suggests to use the getFragmentManager method which does not work for me.
Thanks.
Here is DrawerItemClickListener class:
package com.freestylers.druskischool;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.AdapterView;
public class DrawerItemClickListener implements ListView.OnItemClickListener
{
public int FragmentNumber;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long
id) {
selectItem(position);
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new StartFragment();
FragmentNumber=0;
break;
case 1:
fragment = new MesFragment();
FragmentNumber=1;
break;
case 2:
fragment = new NaujienosFragment();
FragmentNumber=2;
break;
case 3:
fragment = new InstruktoriaiFragment();
FragmentNumber=3;
break;
case 4:
fragment = new MetodikaFragment();
FragmentNumber=4;
break;
case 5:
fragment = new GalerijaFragment();
FragmentNumber=5;
break;
case 6:
fragment = new InstruktoriaiFragment();
FragmentNumber=6;
break;
case 7:
fragment = new AtsiliepimaiFragment();
FragmentNumber=7;
break;
case 8:
fragment = new DrufunparkFragment();
FragmentNumber=8;
break;
case 9:
FragmentNumber=9;
fragment = new KontaktaiFragment();
break;
default:
break;
}
if (fragment != null) {
//tutorial suggests this code:
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
getActionBar().setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
And here is my MainActivity.java:
package com.freestylers.druskischool;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
public class MainActivity extends ActionBarActivity {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
ViewPager pager;
FragmentStatePagerAdapter adapter2;
/* Just some random URLs
*
* Each page of our pager will display one URL from this array
* Swiping, to the right will take you to the next page having
* the next URL.
*/
String[] fragments={
"start",
"mes",
"naujienos",
"instruktoriai",
"metodika",
"galerija",
"kainos",
"atsiliepimai",
"drufunpark",
"kontaktai"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[10];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Pradžia");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_copy, "Mes");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Naujienos");
drawerItem[3] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Instruktoriai");
drawerItem[4] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Metodika");
drawerItem[5] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Galerija");
drawerItem[6] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Kainos");
drawerItem[7] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Atsiliepimai");
drawerItem[8] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Drufunpark");
drawerItem[9] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Kontaktai");
mNavigationDrawerItemTitles=
getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this,
R.layout.listview_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
pager=(ViewPager)findViewById(R.id.my_pager);
adapter2=new FragmentStatePagerAdapter(
getSupportFragmentManager()
){
#Override
public int getCount() {
// This makes sure getItem doesn't use a position
// that is out of bounds of our array of fragments
return fragments.length;
}
#Override
public Fragment getItem(int position) {
// Here is where all the magic of the adapter happens
// As you can see, this is really simple.
//(fragments[position]);
if(position==0){
return StartFragment.newInstance();
}
else if(position==1){
return MesFragment.newInstance();
}
else if(position==2){
return NaujienosFragment.newInstance();
}
else if(position==3){
return InstruktoriaiFragment.newInstance();
}
else if(position==4){
return MetodikaFragment.newInstance();
}
else if(position==5){
return GalerijaFragment.newInstance();
}
else if(position==6){
return KainosFragment.newInstance();
}
else if(position==7){
return AtsiliepimaiFragment.newInstance();
}
else if(position==8){
return DrufunparkFragment.newInstance();
}
else if(position==9){
return KontaktaiFragment.newInstance();
}
else{return KontaktaiFragment.newInstance();}
}
};
//Let the pager know which adapter it is supposed to use
pager.setAdapter(adapter2);
}
#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) {
// 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();
itu f (id == R.id.action_start) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle other action bar items...
/* switch (item.getItemId()) {
case R.id.action_settings:
return true;
}*/
return super.onOptionsItemSelected(item);
}
public static void ChooseFragment(Fragment fragment) {
}
}

I figured out my mistake, it all has to be inside MainActivity.java, DrawerItemClickListener is an inner class.
Still have not found a way to navigate between swipeable fragments from the navDrawer, probably it is impossible.

Related

In ListView make the first item as a title ,and index issue

I am trying to display the title for the Navigation Drawer,It displayed properly but the problem is that when I am trying to click on the first item in the navigation drawer that is home ,it will display the Queues.class instead of expected class.And when click on the last item in the navigation Drawer application get crash.I just want to Display the Title in the navigation Drawer and last item click will show proper activity.Also problem is that the title display two times.
package com.abc;
//import android.app.Activity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.R.*;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.BaseBundle;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class navigation_drawer_class extends Activity
//public class navigation_drawer_class extends ListActivity
{
private static final int Copy = 0;
int a =0;
public static FrameLayout frameLayout;
TextView mytextview;
public static ListView mDrawerList;
public DrawerLayout mDrawerLayout;
String Fullname;
protected String[] listArray = {"Home","Queue","Inbox","Create Ticket","Search","Clients","App settings"};
protected static int position;
private static boolean isLaunch = true;
//*****************************************
JSONObject post_details_obj,post_obj;
public static String FIRST_NAME="first_name",LAST_NAME="last_name";
JSONArray staff_data_array;
//*****************************************
private ActionBarDrawerToggle actionBarDrawerToggle;
Operation op=new Operation();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//------------------ THIS ONE -------------------------
getActionBar().setHomeAsUpIndicator(R.drawable.crop3);//THIS ONE FOR THE DRAWER LOGO
//--------------------- THIS ONE ----------------------
frameLayout = (FrameLayout)findViewById(R.id.content_frame);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
/// mDrawerList.setAdapter(null);
//***************** To Set the Welcome client ******************************************
//========= THIS ONE ===============
new getname().execute();
//========= THIS ONE ===============
/* mDrawerList.setAdapter(null);
View header = (View)getLayoutInflater().inflate(R.layout.headerview,null);
TextView headerValue = (TextView) header.findViewById(R.id.headerview_id);
headerValue.setText("Mydata");
mDrawerList.addHeaderView(header, null, false);//addHeaderView(header, null, false)
*/
/* TextView tv=new TextView(getApplicationContext());
Log.d("Fullname in oncreate : ",Fullname.toString());
tv.setText(Fullname); */
//******************To Set the Welcome client ******************************************
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listArray));
mDrawerList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
openActivity(position);
}
});
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, // host Activity
mDrawerLayout, // DrawerLayout object
R.drawable.ic_launcher, // nav drawer image to replace 'Up' caret
R.string.open_drawer, // "open drawer" description for accessibility
R.string.close_drawer) // "close drawer" description for accessibility
{
#Override
public void onDrawerClosed(View drawerView)
{
getActionBar().setTitle(listArray[position]);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(getString(R.string.app_name));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
}
#Override
public void onDrawerStateChanged(int newState)
{
super.onDrawerStateChanged(newState);
}
};
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
if(isLaunch){
isLaunch = false;
openActivity(0);
}
}
protected void openActivity(int position) {
// mDrawerList.setItemChecked(position, true);
// setTitle(listArray[position]);
mDrawerLayout.closeDrawer(mDrawerList);
navigation_drawer_class.position = position; //Setting currently selected position in this field so that it will be available in our child activities.
switch (position) {
case 0:
startActivity(new Intent(this, Folders.class));
break;
//case 2:
case 1:
Intent i=new Intent(navigation_drawer_class.this,Queues.class);
i.putExtra("set_queue","set");
startActivity(i);
break;
case 2:
//case 3:
Intent inbox=new Intent(navigation_drawer_class.this,Tickets.class);
inbox.putExtra("filter_id","&vis_filter_id=1");
inbox.putExtra("title","Inbox");
inbox.putExtra("set_queue","no");
startActivity(inbox);
break;
case 3:
//case 4:
startActivity(new Intent(this, New_Ticket_step1.class));
break;
case 4:
//case 5:
startActivity(new Intent(this, Search.class));
break;
case 5:
//case 6:
startActivity(new Intent(this, Client.class));
break;
case 6:
//case 7:
startActivity(new Intent(this, Settings.class));
break;
default:
break;
}
/*
switch (position) {
case 0:
break;
case 1:
startActivity(new Intent(this, Folders.class));
break;
case 2:
Intent i=new Intent(navigation_drawer_class.this,Queues.class);
i.putExtra("set_queue","set");
startActivity(i);
break;
case 3:
Intent inbox=new Intent(navigation_drawer_class.this,Tickets.class);
inbox.putExtra("filter_id","&vis_filter_id=1");
inbox.putExtra("title","Inbox");
inbox.putExtra("set_queue","no");
startActivity(inbox);
break;
case 4:
startActivity(new Intent(this, New_Ticket_step1.class));
break;
case 5:
startActivity(new Intent(this, Search.class));
break;
case 6:
startActivity(new Intent(this, Client.class));
break;
case 7:
startActivity(new Intent(this, Settings.class));
break;
default:
break;
}
*/
//Toast.makeText(this, "Selected Item Position::"+position, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
switch (item.getItemId())
{
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/* We can override onBackPressed method to toggle navigation drawer*/
#Override
public void onBackPressed()
{
if(mDrawerLayout.isDrawerOpen(mDrawerList))
{
mDrawerLayout.closeDrawer(mDrawerList);
}
else
{
mDrawerLayout.openDrawer(mDrawerList);
}
}
//-----------------------------------------------------------
private class getname extends AsyncTask<Void, Void, JSONArray>
{
Dialog dialog;
#Override
public void onPreExecute()
{
dialog = new Dialog(navigation_drawer_class.this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
String STAFF_URL=op.getUrl(getApplicationContext(),"staff","get_staff_details","");
staff_data_array = JSONfunctions.getJSONfromURL(STAFF_URL+"&vis_encode=json",navigation_drawer_class.this);
return staff_data_array;
}
#Override
public void onPostExecute(JSONArray staff_data_array)
{
super.onPostExecute(staff_data_array);
String staff_data_result =staff_data_array.toString();
try {
post_obj = staff_data_array.getJSONObject(0);
String fname=post_obj.getString(FIRST_NAME);
String lname=post_obj.getString(LAST_NAME);
//Fullname =fname+" "+lname;
Fullname =fname;
if(Fullname=="")
{
Fullname="Admin";
}
Fullname="Welcome "+Fullname;
View header = (View)getLayoutInflater().inflate(R.layout.headerview,null);
TextView headerValue = (TextView) header.findViewById(R.id.headerview_id);
headerValue.setText(Fullname);
mDrawerList.addHeaderView(header, null, false);//addHeaderView(header, null, false) */
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}
//-----------------------------------------------------------
}

how to go back to previous fragment when hardware back button is pressed

i am begineer in android development , i would like to configure hardware backbutton to go back to previous fragment and the fragment titles should also change according to the current fragment ,
here is my Main activity source :
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#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;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new MicrosoftDskFragment();
title = "Microsoft Dsk";
break;
case 2:
fragment = new GoogleDskFragment();
title = "Google Dsk";
break;
case 3:
fragment = new AppleDskFragment();
title = "Apple Dsk";
break;
case 4:
fragment = new OthersDskFragment();
title = "Others Dsk";
break;
case 5:
fragment = new AboutUSFragment();
title = "About US";
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.addToBackStack(null).commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
plz hel me in fixing this .
You are adding the transaction to the backstack, so all you should need in order to get back to the previous one should be:
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackstack(null, 0);
You may also consider adding an id for each fragment and passing it when calling
fragmentTransaction.addToBackStack(null).commit();
instead of the null. This way, you will be able to do this:
fragmentTransaction.addToBackStack(myFragmentId).commit();
//Later on...
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackstack(myFragmentId, 0);
To go back to a specific fragment, not just the last one :-)
every time when you add a fragment just add addToBackStack() method before commit and then in your activity on back pressed try this
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 1) {
goToExitApplication(
getResources().getString(R.string.close_app), true);
} else {
String title = getSupportFragmentManager().getBackStackEntryAt(count - 2).getName();
getSupportFragmentManager().popBackStack();
getSupportActionBar().setTitle(title);
}
}
I have used this in my code:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0 ){
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
To push the Fragment I used:
MyFragment_Items myf = new MyFragment_Items();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_layout, myf);
transaction.addToBackStack(null);
transaction.commit();
I pushed the fragment here and popped it back onBackPressed.
It will Surely work for you If there is any Fragment on the back stack of current fragment , popBackStackImmediate() works..
#Override
public void onBackPressed() {
if(getFragmentManager().getBackStackEntryCount() > 0){
getFragmentManager().popBackStackImmediate();
}
else{
super.onBackPressed();
}
}

Navigation Drawer and ViewPager conflict

I'm currently developing an android application where I'm using a navigation drawer as well as the swipe gesture using viewPager to traverse through fragments.
Basically, I want the user to be able to select pages (fragments) using the navigation drawer and be able to swipe to the next page (fragment).
My problem right now is that they overlap. The swipe gesture works as expected but when I select another page on the nav drawer they underlying page doesn't disappear. I need someway to "refresh" each fragment.
Here is my code in the MainActivity.java page
package com.example.home.cloud;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private static final int NUM_PAGES = 10;
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new MyFragmentStatePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class MyFragmentStatePagerAdapter extends FragmentStatePagerAdapter
{
public MyFragmentStatePagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position) {
final Fragment result;
switch (position) {
case 0:
result= new HomeFragment();
break;
case 1:
result= new OverviewFragment();
break;
case 2:
result= new BenFragment();
break;
case 3:
result= new TechFragment();
break;
case 4:
result= new ArcFragment();
break;
case 5:
result= new DmodFragment();
break;
case 6:
result= new SmodFragment();
break;
case 7:
result= new VirtFragment();
break;
case 8:
result= new StorageFragment();
break;
case 9:
result= new SecurityFragment();
break;
default: result=null;
break;
}
/* if (result != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, result);
fragmentTransaction.commit();
}*/
return result;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
#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;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new OverviewFragment();
title = getString(R.string.title_overview);
break;
case 2:
fragment=new BenFragment();
title="Benefits and Risks";
break;
case 3:
fragment=new TechFragment();
title="Technologies behind Cloud Computing";
break;
case 4:
fragment = new ArcFragment();
title="Architecture";
break;
case 5:
fragment= new DmodFragment();
title="Deployment Models";
break;
case 6:
fragment = new SmodFragment();
title="Service Models";
break;
case 7:
fragment = new VirtFragment();
title="Virtualization";
break;
case 8:
fragment = new StorageFragment();
title="Data Storage";
break;
case 9:
fragment = new SecurityFragment();
title="Security";
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
The trouble is that you're displaying your fragments in two different ways. Your displayView() method is creating new fragments and displaying them, rather than showing the ones which are already loaded in the ViewPager. To fix this, you need displayView() to instead set your ViewPager position.
private void displayView(int position) {
mPager.setCurrentItem(position);
getSupportActionBar().setTitle(mPagerAdapter.getPageTitle(position));
}

Item not highlighted in navigation drawer

I'm trying to create a navigation drawer. I have created it but the problem is that when i open the app the first time, the fragment is displayed in the content area but it is not highlighted in the navigation drawer.
This is code i'm using:
package com.hfad.evenit;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.hfad.evenit.Fragments.FourthFragment;
import com.hfad.evenit.Fragments.SecondFragment;
import com.hfad.evenit.Fragments.ThirdFragment;
import com.hfad.evenit.Fragments.TopFragment;
public class Home extends AppCompatActivity {
String []FragmentTitles;
ListView DrawerList;
DrawerLayout drawerLayout;
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
FragmentTitles = getResources().getStringArray(R.array.fragment_titles);
DrawerList = (ListView) findViewById(R.id.drawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
DrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, FragmentTitles));
DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
selectItem(0);
DrawerList.setSelection(0);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open_drawer, R.string.close_drawer) {
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = drawerLayout.isDrawerOpen(DrawerList);
menu.findItem(R.id.action_share).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#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_home, 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.
if(drawerToggle.onOptionsItemSelected(item))
{
return true;
}
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void selectItem(int position)
{
Fragment fragment;
switch(position)
{
case 0:
fragment = new TopFragment();
break;
case 1:
fragment = new SecondFragment();
break;
case 2:
fragment = new ThirdFragment();
break;
case 3:
fragment = new FourthFragment();
break;
default:
fragment = new TopFragment();
}
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
setActionBarTitle(position);
drawerLayout.closeDrawer(DrawerList);
}
public void setActionBarTitle(int position)
{
String title;
title = FragmentTitles[position];
getSupportActionBar().setTitle(title);
}
}
The method you should use for changing the items state to "highlighted" or currently activated is setItemChecked(int position, boolean value). It's best to place it in your selectItem method so that the "highlighted" item changes once your SelectItem method is called.
You might also want to consider setting the listView's choice mode to CHOICE_MODE_SINGLE so that only one item can be in an active state at a given time.
drawerList.setChoiceMode(CHOICE_MODE_SINGLE);
Around here...
public void selectItem(int position) {
...
setActionBarTitle(position);
drawerLayout.closeDrawer(DrawerList);
}
Adding DrawerList.setItemChecked(position, true); may work.
public void selectItem(int position) {
...
setActionBarTitle(position);
DrawerList.setItemChecked(position, true); // <== add this line
drawerLayout.closeDrawer(DrawerList);
}
Actually I'm not using Navigation Drawer of the Android Studio's project template but using NavigationView (it is recommended for ease to use), recently. If my answer is invalid, please forget this.

Play Store Arrow Animation in Navigation Drawer

Last week I started developing on android. I'm making an app for the gym where I train. I've made the main functions so far but i'm stuck trying to add the animation when the navigation drawer is opened or closed. Right now the navigation drawer is fully functional but the arrow doesn't animate as you can see from the picture:
Image
This is the link to the project made with Android Studio:
App
This is the Main Activity. java of the app:
package com.dev.lollos.argus1910;
import android.app.Activity;
import android.content.Intent;
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.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
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.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainMenu extends android.support.v7.app.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;
public void OpenSettings(View view) {
// Do something in response to button
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
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
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
switch(position) {
default:
case 0:
fragment = new Home_Fragment();
break;
case 1:
fragment = new Atleti_Fragment();
break;
case 2:
fragment = new Societa_fragment();
break;
case 3:
fragment = new Manifestazioni_Fragment();
break;
case 4:
fragment = new Risultati_Fragment();
break;
case 5:
fragment = new Storia_Fragment();
break;
}
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;
case 4:
mTitle = getString(R.string.title_section4);
break;
case 5:
mTitle = getString(R.string.title_section5);
break;
case 6:
mTitle = getString(R.string.title_section6);
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, 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);
}
public void OpenSettings(MenuItem item) {
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
}
/**
* 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_menu, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainMenu) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
I hope you can help me. Thanks in advance
You need to sync the drawer:
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(<context>, drawerLayout, 0, 0, 0);
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();

Categories

Resources