how to control the back navigation button in a activity - android

I have implemented a tab layout with swipeable views, it has 5 tabs.
in my 1st four tabs i have loaded grid menus. if i select one of those items in da grid it will open a new activity.
in my manifest.xml file i have used this line to navigate it back.
android:parentActivityName="xxxxxxx.ActivityMenuGrid"
when i select an item in my 2nd,3rd or 4th tabs and press the back navigation button on left top corner of my screen then it will go back to and open up and display the 1st tab, not the tab where i selected the required item.
but if i press the back button in my phone it will navigate me back to the tab where i open the new activity.
how can i navigate my back navigation in my left top corner to the appropriate tab.
public class ActivityMenuGrid extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
public TabHost myTabHost;
// Tab titles
private String[] tabs = { "", "", "", "", "" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.addTab(actionBar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_tab_p));
actionBar.addTab(actionBar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_tab_n));
actionBar.addTab(actionBar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_tab_s));
actionBar.addTab(actionBar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_tab_pr));
actionBar.addTab(actionBar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_tab_pro);
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// set background for action bar tab
bar.setStackedBackgroundDrawable(new ColorDrawable(Color
.parseColor("#f8f8f8")));
bar.show();
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
public void onBackPressed() {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
// Associate searchable configuration with the SearchView
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_search:
// search action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// getActionBar().setTitle(tab.getText());
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
im selecting a item from tab2,
then it will openup new activity. and it has back navigation button.
when i press the back navigation button then it will go back to the tab1, not tab 2. I want to fix that issue and navigate it to tab2.
FYI- when i press the back navigation hardware button in the phone it will navigate it to tab 2.
any help will be highly appreciated.

you have to override the activitys onBackPresed function and have to write the logic to to move to the'desired tab. doing this will prevent your app from close(default navigation on back button pressed) with android hardware back button, also you have to check if you are in desired tab already and pass the event super.onBackPressed(); to the OS to close the app or handle tha default navigation.

The below code states when you press back button it is starting new activity and you are not overriding that.Check once with that.
#Override - > Missing.
public void onBackPressed() {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
I would suggest one edit
Try to set position of the tab in onPageSelected method and when back pressed check the previous position where it exactly and navigate to it.
Ex :
static int pos =0;
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
pos=position;
}
#Override
public void onBackPressed() {
try {
switch (pos) {
case 0: // Means Main Activity : Do Default action
super.onBackPressed();
break;
case 1:
case 2:
case 3://Other than main tab open previous positioned tab.
viewPager.setCurrentItem(pos, true);
break;
}
} catch (Exception e) {
super.onBackPressed();
}
}
I had same problem and it worked for me.Glad if i could help you.

I was able to achive it by doing,
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Related

How to make bottom navigation selected automatically when moving from one fragment to another?

I'm trying to make action button to move from the home fragment to the promo fragment.
In the fragment home there is an action button that will move to the promo fragment. However, when the promo action button on the home fragment is clicked, the display will move to the promo fragment but the bottom navigation is still selected in the home fragment.
Screenshot Home Fragment
Screenshot Promo Fragment
This is my action button code in Home Fragment:
imagePromo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).selectFragment(2);
}
});
This is my selectfragment code in MainActivity:
public void selectFragment(int position){
viewPager.setCurrentItem(position, true);
viewPager.dispatchSetSelected(true);
}
This is my bottom navigation code in MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = findViewById(android.R.id.content);
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(pager_number);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(item -> {
switch (item.getItemId()) {
case R.id.navigation_home:
viewPager.setCurrentItem(0);
return true;
case R.id.navigation_category:
viewPager.setCurrentItem(1);
return true;
case R.id.navigation_promo:
viewPager.setCurrentItem(2);
return true;
case R.id.navigation_wishlist:
viewPager.setCurrentItem(3);
return true;
}
return false;
});
}
I'm trying to use the code I found on github. Below is the code snippet:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
} else {
navigation.getMenu().getItem(0).setChecked(false);
}
navigation.getMenu().getItem(position).setChecked(true);
prevMenuItem = navigation.getMenu().getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
I tried to apply it in MainActivity and it solved my problem above.
You can set it in your setOnClickListener to change the Fragment of the ViewPager and it's CurrentItem to get the icon changed aswell.
Button to_promo = view.findViewById(R.id.to_promo);
to_promo.setOnClickListener(view1 -> {
viewPager.setCurrentItem(2);
});

How to add back button on action bar with more tabs

know anyone how can I add one back button on my action bar? I want to add the back button befor INFO tab. I've try some method but no one of them don't work for me. Well let's start with started.
In this image in left part it's what I need to do as actionbar and in the right part it's how looks my project right now.
I've try to put that code for add the back button but it don't works:
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeButtonEnabled(true);
Here it's my Activity:
public class TrailActivity extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
Intent intent;
Trail trail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intent = getIntent();
setContentView(R.layout.trail_fracment_main);
trail = intent.getParcelableExtra("trail");
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeButtonEnabled(true);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
InfoFragments infoFragments = new InfoFragments();
infoFragments.setTrail(trail);
Fragment fragment = infoFragments;
return fragment;
} else if (position == 1) {
return new MapFragments();
} else {
return new WondersFragments();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
Some one told me to try to implement OnBackStackChangedListener and after that he want to put in my code and that:
#Override
public void onCreate(Bundle savedInstanceState) {
//Listen for changes in the back stack
getSupportFragmentManager().addOnBackStackChangedListener(this);
//Handle when activity is recreated like on orientation Change
shouldDisplayHomeUp();
}
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
public void shouldDisplayHomeUp(){
//Enable Up button only if there are entries in the back stack
boolean canback = getSupportFragmentManager().getBackStackEntryCount()>0;
getSupportActionBar().setDisplayHomeAsUpEnabled(canback);
}
#Override
public boolean onSupportNavigateUp() {
//This method is called when the up button is pressed. Just the pop back stack.
getSupportFragmentManager().popBackStack();
return true;
}
Also I've try to add and that override method, but again... nothing happen :(
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I've try and that... but again... I've don't obtain any result :(.
So please guys, if anyone know how can I solve that problem, please show me.. I really need to do that and how much fast is possible.

FragmentPagerAdapter getItem() is returning more than it should

I have a MainActivity that controls four fragments, each of which is a tab. When my main activity starts, I have a line being printed to the log to show me what fragment is being instantiated. Here is my FragmentPagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
System.out.println("Returning new PrearrivalPlan()");
return new PrearrivalPlan();
case 1:
System.out.println("Returning new PrimarySurvey()");
return new PrimarySurvey();
case 2:
System.out.println("Returning new SecondarySurvey()");
return new SecondarySurvey();
case 3:
System.out.println("Returning new PrepareForTravel()");
return new PrepareForTravel();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
The tab bar has the following options in order:
Prearrival Plan | Primary Survey | Secondary Survey | Prepare for Travel
When my main activity starts, the following is printed to the screen:
Returning new PrearrivalPlan()
Returning new PrimarySurvey()
What it seems to be doing is loading one tab ahead of the one I have selected. Since PrearrivalPlan is the first tab, I would think it should just return a new PrearrivalPlan() except it returns both. Another example, when I click on Primary Survey tab (second tab), the following is printed to the screen:
Returning new SecondarySurvey() // <- This is the third tab!?
Because PrimarySurvey was already instantiated when the activity first started (see output above), it jumped ahead just like it did before and loaded the third tab even though I only clicked on the second.
Here is my MainActivity:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private CustomViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabTitles = {"Pre-arrival Plan", "Primary Survey", "Secondary Survey", "Prepare for Travel"};
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (CustomViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
viewPager.setPagingEnabled(false);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager.setOnPageChangeListener(new CustomViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
// Remove Android icon from Action Bar
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
getActionBar().setDisplayShowHomeEnabled(false);
// Add tabs to Action Bar
for (String tab_name : tabTitles) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void updateTabTitles(int tabNumber, int checkBoxesRemaining) {
String text = tabTitles[tabNumber] + " \n (" + checkBoxesRemaining + ")";
actionBar.getTabAt(tabNumber).setText(text);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
return true;
case R.id.complete:
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
goToReport();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to complete the checklist?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToReport() {
Intent intent = new Intent(this, Report.class);
startActivity(intent);
}
It is the expected behaviour of ViewPager. ViewPager always keeps one tab ahead and behind in memory in order to show slider animation. If you don't you have the next or previous tab (or fragment) in memory, trying to initiate the fragment during the slider transition will cause a performance lag or at the worse you will have the sliding fragment to be empty and get loaded later.
ViewPager also allows you to set page offset limit through setOffscreenPageLimit() which will control amount fragment to keep them in memory. By default, this is 1 which means one fragment ahead and behind will always be there in memory

How i operation on Back Button in fragment. ask for back button of hardware of phone

i want to operation on back button in main fragment class. i am use swipe tab with help of fragment. so in as par activity class i know function of back button. but this is not help of me. this is my code. i already done on action bar home function. so i want to do same as back button
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Metals","Forex" };
static int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
i=0;
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
// actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
Log.d("back", "backkk");
i = 1;
Toast.makeText(getApplicationContext(), "back"+i,100).show();
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
i think you want to perform an opration when back key is pressed in Fragment
So Create a public method in fragment
and from Fragment activity class , override onBackkeypressed call that method
example
#Override
public void onBackPressed() {
DetailFragment fragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.listfragment);
fragment.doSomthing()
}

How to make an Android refresh button that refreshes the fragment in a drawer?

I am trying to refresh the fragment depending on what drawer the user is on...
This was my attempt which does not do anything but does not give me an error.
Here is my code
public void fragmentRefresh() {
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragmentManager.findFragmentByTag("TagForRefresh"))
.commit();
}
Here is the drawer fragment code:
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new BrowseFragment();
break;
case 2:
fragment = new InviteFragment();
break;
case 3:
fragment = new ProfileFragment();
break;
case 4:
fragment = new SettingsFragment();
break;
case 5:
callConfirmLogout();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment, "TagForRefresh").commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
Implemented in a tab swiper fragment class:
public class ViewVotesActivity extends FragmentActivity implements ActionBar.TabListener{
//Tab options
private ViewPager viewPager;
private TabSwipeAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Created", "Up", "Down"};
//for custom menu to add progress bar to refresh
private MenuItem menuItem;
//Search view action bar
private SearchView search_action_bar;
//getApplicationContext().getString(R.string.created),getApplicationContext().getString(R.string.upvote), getApplicationContext().getString(R.string.downvote)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_votes);
// Initializing tab
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabSwipeAdapter(getSupportFragmentManager(), new UserCreatedFragment(), new UserUpVotesFragment(),new UserDownVotesFragment());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
setupActions(menu);
callSearchActionBar(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_refresh:
menuItem = item;
menuItem.setActionView(R.layout.refresh_progress_bar);
//menuItem.expandActionView();
fragmentRefresh();
TestTask task = new TestTask();
task.execute("test");
return true;
case R.id.action_discover:
addNewItem();
return true;
case R.id.action_search:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void addNewItem() {
// user redirect to register followup
Intent createItemIntent = new Intent(ViewVotesActivity.this, CreateItemActivity.class);
// Closing all the Activities
createItemIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
createItemIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(createItemIntent);
}
public void fragmentRefresh() {
// // Insert the fragment by replacing any existing fragment
// FragmentManager fragmentManager = getFragmentManager();
//
// fragmentManager.beginTransaction()
// .replace(R.id.frame_container, fragmentManager.findFragmentByTag("TagForRefresh"))
// .commit();
}
private class TestTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Simulate something long running
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
menuItem.collapseActionView();
menuItem.setActionView(null);
}
};
public void setupActions(Menu menu) {
MenuItem refreshItem = menu.findItem(R.id.action_refresh);
MenuItem discoverItem = menu.findItem(R.id.action_discover);
if (isAlwaysExpanded()) {
} else {
refreshItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
discoverItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
}
public void callSearchActionBar(Menu menu) {
//find the menu item and set search view at the same time
MenuItem searchItem = menu.findItem(R.id.action_search);
search_action_bar
= (SearchView) searchItem.getActionView();
if (isAlwaysExpanded()) {
search_action_bar.setIconifiedByDefault(false);
} else {
searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if (searchManager != null) {
List<SearchableInfo> searchables = searchManager.getSearchablesInGlobalSearch();
SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
for (SearchableInfo inf : searchables) {
if (inf.getSuggestAuthority() != null
&& inf.getSuggestAuthority().startsWith("applications")) {
info = inf;
}
}
search_action_bar.setSearchableInfo(info);
}
search_action_bar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
Log.e("Query = ", newText);
return false;
}
public boolean onQueryTextSubmit(String query) {
Log.e("Submit", "Submited " + query);
// user redirect to register followup
Intent searchIntent = new Intent(ViewVotesActivity.this, SearchActivity.class);
searchIntent.putExtra("search", query);
// Closing all the Activities
searchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
searchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(searchIntent);
return false;
}
public boolean onClose() {
Log.e("query close", "query closingggg");
return false;
}
});
}
protected boolean isAlwaysExpanded() {
return false;
}
}
UPDATE:
It looks like you're trying to tell an Activity that it's time to change the content fragment depending upon a selection in a Navigation Drawer.
This problem has two parts.
You need to provide a mechanism to communicate from your Drawer to your Activity, which, will, in turn, proceed to perform the necessary actions.
Your Fragments must either be Detached, Destroyed, Recreated and Reattached (inneficient, why?) or simply implement a mechanism that tells them: Hey, it's time to Refresh your content.
I don't see any reason why you need to completely destroy the Fragment's view if you only need to reset its data. Seems like a design flaw.
Replacing a Fragment should not mean you want to completely destroy it, since the user can simply go back or press the recently removed fragment. It would be inefficient to recreate it again.
Like I mentioned in the comments, more code is needed to see what your current approach is.
Normally a simple Interface (like the one I described below) should suffice. Your activity can receive the "clicks" in the Drawer and decide which fragment to replace (if needed).
Please be a lot more specific and provide more code.
Old Response:
Warning: if you're trying to replace the current fragment, make sure you're not getting the wrong FragmentManager. You do getFragmentManager() but I'm sure you're using the support library and therefore need to do getSupportFragmentManager();.
You've failed to mention what version you're targeting so it's hard to know.
On the other hand,
If what you want to do is tell the current visible fragment to refresh… you should use a more common approach to object-to-object communication.
You're over-complicating things.
(warning: pseudo code)
Create an interface like:
public interface Refreshable{
void onShouldRefresh();
}
Have a DrawerController capable of storing observers/listeners…
public class DrawerController {
private List<Refreshable> mListeners = new ArrayList<Refreshable>();
public void addRefreshListener(E listener) {
if (listener != null && !mListeners.contains(listener)) {
mListeners.add(listener);
}
}
public void removeRefreshListener(E listener) {
if (listener != null) {
mListeners.remove(listener);
}
}
}
Make your fragments implement it (and subscribe to the event when they are visible)
public class HomeFragment extends Fragment implements Refreshable {
// your fragment code
public void onShouldRefresh(){
// do the refresh
}
#Override
public void onResume() {
super.onResume();
yourDrawerController.addRefreshListener(this);
}
#Override
public void onPause() {
super.onPause();
yourDrawerController.removeRefreshListener(this);
}
}
Now make a method that will tell the interested parties (in this case your "Refreshable" objects) that it's time to refresh, add this to your DrawerController…
public void refresh(){
for (Refreshable listener : mListeners) {
if (listener != null) {
listener.onShouldRefresh();
}
}
}
Finally, in your code, call refresh() and have a beer.
Did I miss your point? it's not 100% clear to me.

Categories

Resources