Android ViewPager refresh when swipe - android

My fragment is not refreshing when I swipe back, so I want to know how I can refresh it when I swipe it back. I have seen many different answers online, but I don't why they don't work in my situation. It would be highly appreciated if someone could help me out, thanks.
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Profile tab1 = new Profile();
return tab1;
case 1:
Puzzles tab2 = new Puzzles();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Profile";
case 1:
return "Puzzles";
}
return null;
}
}
}
I have tried setOffscreenPageLimit(0), detach attach fragment in onTabSelected, using FragmentStatePagerAdapter, notifyDataSetChanged(), and even
public int getItemPosition(Object object) {
return POSITION_NONE;
}
this doesn't work too. So I hope someone could help.

If you want to refresh the data in a particular Fragment, you have to do 2 things,
Store the updated data into Activity
Show the updated data in onResume() in that particular Fragment
If you want your data to be saved even after killing the app, store it in SharedPreference. Hope it helps!

On your fragment class add this.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//Try adapter.notifyDataSetChanged or something like passing the new(updated) data to adapter from here.
}
}
Hope it helps.

Related

Start a tab fragments from an activity with the tabs layout

I have a tab fragments app. The problem is when I go into an activity inside my app and want going back to my tabs layout it returns without the tabs row layout. I can see only the specific fragment page without the row above (the tab's row) that makes me able to navigate between the tabs.
Do you know what can I do to solve it? How can I see the tab's row too?
Thanks for any help,
This is the first tab that I want to see back from the activity:
public class Tab1MyProfile extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1_my_profile, container, false);
return rootView;
}
}
This is the activity that contains code to go back to the fragment tab:
public class GameLive extends AppCompatActivity implements RecognitionListener {
private Intent intent;
private Button mStopButton;
public void stopGame (View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to finish the game?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Tab1MyProfile fragment = new Tab1MyProfile();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_live);
mStopButton = (Button) findViewById(R.id.btnEndGame);
mStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopGame(view);
}
});
}
}
And this is the activity that contains all the tab's fragment:
public class StartActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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_start, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1MyProfile tab1=new Tab1MyProfile();
return tab1;
case 1:
Tab2StartGame tab2=new Tab2StartGame();
return tab2;
case 2:
Tab3StatsArea tab3=new Tab3StatsArea();
return tab3;
case 3:
Tab4Settings tab4=new Tab4Settings();
return tab4;
}
return null;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "My profile";
case 1:
return "Start Game";
case 2:
return "Stats Area";
case 3:
return "Settings";
}
return null;
}
}
}
Thank again!
What if you replace everything inside the onClick method of the DialogInterface.OnClickListener with GameLive.this.finish();. This will close the GameLive activity on click and return you to the previous activity, which should be the one that contains the missing navigation bar.

Intent From fragment to Second Tab

I have tab layout in android with viewpager in my Main Activity. I have three Tab with three Fragment. And in first fragment i have button i want to intent on second tab from that button on click. how to intent please help me.
Here is my Code
public class MainActivity extends AppCompatActivity {
//Declaring All The Variables Needed
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("first", "str1");
//str1 = intent.getStringExtra("first");
Toast.makeText(MainActivity.this, "" + name, Toast.LENGTH_SHORT).show();
toolbar = (Toolbar) findViewById(R.id.toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
FragmentManager manager = getSupportFragmentManager();
ViewPagerAdapter adapter = new ViewPagerAdapter(manager);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setTabsFromPagerAdapter(adapter);
tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.drawable.tab_selector));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
setSupportActionBar(toolbar);
final FloatingActionMenu floatingActionsMenu=(FloatingActionMenu) findViewById(R.id.material_design_android_floating_action_menu);
final FloatingActionButton floatingActionButton1=(FloatingActionButton)findViewById(R.id.material_design_floating_action_menu_item1);
floatingActionButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Table", Toast.LENGTH_SHORT).show();
viewPager.setCurrentItem(0);
floatingActionsMenu.close(true);
}
});
FloatingActionButton floatingActionButton2=(FloatingActionButton)findViewById(R.id.material_design_floating_action_menu_item2);
floatingActionButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Order", Toast.LENGTH_SHORT).show();
viewPager.setCurrentItem(1);
floatingActionsMenu.close(true);
}
});
FloatingActionButton floatingActionButton3=(FloatingActionButton)findViewById(R.id.material_design_floating_action_menu_item3);
floatingActionButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Logout", Toast.LENGTH_SHORT).show();
}
});
}
#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 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) {
Intent tologin=new Intent(MainActivity.this,LoginPage.class);
startActivity(tologin);
return true;
}
return super.onOptionsItemSelected(item);
}
}
All the fragments are within the same ViewPager and you just want to go one to another fragment you can do like this...
The view pager is in Activity but the Button is inside Fragment so you need to do this create this method inside your activity
public void navigateFragment(int position){
viewPager.setCurrentItem(position, true);
}
and call inside your OnClickListener method of fragment:
((MainActivity)getActivity()).navigateFragment(POSITION_YOU_WANNA_SELECT);
Hope this will help you.
Recommended approach : you can implement a listener in second fragment and create reference in first fragment.
after onclick of a button from 1st fragment call method of listener which is defined in second fragment.
Second approach : you can maintain a static data from 1st fragment and on click just load 2nd fragment and access that static data.

ViewPager always starts from 0th position

I have a RecyclerView in a Fragment which is in a ViewPager hosted in an Activity. There's two Activities in this project MainActivity which lists items and DetailActivity which shows details about the item chosen in the first activity.
When I move from DetailsActivity to MainActivity I am always take to ViewPager Fragment position 0 which is the first Fragment. How can I restore the fragment position?
Bundle is always empty when I move from DetailActivity to MainActivity.
Here is the full code of the app.
MainActivity
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private static final String LOG = MainActivity.class.getSimpleName();
private static final String VIEWPAGER_POSITION = "currentItem";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_titles);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
if (savedInstanceState != null) {
int pos = savedInstanceState.getInt(VIEWPAGER_POSITION, 0);
Log.d(LOG, "onCreate pos: " + pos);
mViewPager.setCurrentItem(pos);
} else {
Log.d(LOG, "onCreate savedInstanceState is null");
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new PopularFragment(), getResources().getString(R.string.popularity));
adapter.addFragment(new RatingFragment(), getResources().getString(R.string.rating));
adapter.addFragment(new FavoriteFragment().newInstance(), getResources().getString(R.string.favorite));
viewPager.setAdapter(adapter);
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#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;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
int pos = mViewPager.getCurrentItem();
Log.d(LOG, "onSaveInstanceState pos: " + pos);
bundle.putInt(VIEWPAGER_POSITION, mViewPager.getCurrentItem());
}
}
Thanks.
I am shooting, when you go back from DetailActivity, look for Bundle in
this.getIntent().getExtras().getInt(VIEWPAGER_POSITION, 0)
UPDATE:
if you need persist your current position in for example SharedPreferences in onPause and retrieve it in onResume. like:
private static String MY_PAGER_TAG = "tag_of_shared_vp_position";
public void onPause(){
super.onPause();
int pos = getCurrentViewPagerPosition();//custom function, implement it by //yourself
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(MY_PAGER_TAG, pos);
editor.commit();
}
public void onResume(){
super.onResume();
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int pos = sharedPref.getInt(MY_PAGER_TAG,0);
setUpViewPagerOnPosition(pos);
}
I noticed that if I pressed the physical back button the ViewPager and RecyclerView were properly restored. So I wanted a way to set up button behavior same as onBackPressed(). Answer to which has already been posted in the question Make the “up” button behave like the “back” button on Android.
I made following changes in DetailActivity and my code started working just fine.
#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 == android.R.id.home) {
onBackPressed();
return true;
}
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

Android - Keeping SearchView opened in Fragment ViewPager

So.. I have a Fragment containing ViewPager with two more Fragments in it which serves as search tabs. That means 3 different Java classes, 1 for container, the 2 are for the contents.
The behavior I wanted was : When user presses the search button, types something, and submit the search in the base Activity, the app overrides onQueryTextSubmit to start the pager Fragment and getting the query there to directly search in the first Fragment in the pager. When user swipe to the next Fragment, the SearchView persists, along with its query and also perform search on the second Fragment using said query.
The behavior I am getting is.. When user swipes to the next Fragment, the searchmenu collapses and the keyword is gone..
This is how I code the SearchVenu in the Activity
#Override
public boolean onQueryTextSubmit(String query) {
searchFragment = new SearchFragment();
Bundle searchBundle = new Bundle();
keyword = searchView.getQuery().toString();
searchBundle.putString("searchQuery", keyword);
searchFragment.setArguments(searchBundle);
backstackCount = manager.getBackStackEntryCount();
if (backstackCount >= 2) {
manager.executePendingTransactions();
if (manager.getBackStackEntryAt(backstackCount - 1).getName().equals("searchTag")) {
} else {
replaceFragment(searchFragment, searchTag);
}
} else {
replaceFragment(searchFragment, searchTag);
}
return false;
The adapter :
mAdapter = new MyPagerAdapter(getChildFragmentManager(), bundle);
...
private class MyPagerAdapter extends FragmentStatePagerAdapter {
private Bundle fragmentBundle;
public MyPagerAdapter(FragmentManager fm, Bundle data) {
super(fm);
fragmentBundle = data;
}
#Override
public Fragment getItem(int pos) {
/*Fragment f = new Fragment();
f.setArguments(this.fragmentBundle);
return f;*/
switch(pos) {
case 0: return SearchFriendFragment.newInstance(fragmentBundle);
case 1: return SearchShopFragment.newInstance(fragmentBundle);
default: return SearchFriendFragment.newInstance(fragmentBundle);
}
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length];
}
#Override
public int getCount() {
//return 3;
return CONTENT.length;
}
}
This is how I initialize the search in one of the Fragments
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
super.onPrepareOptionsMenu(menu);
getActivity().getMenuInflater().inflate(R.menu.menu_search, menu);
searchViewBtn = menu.findItem(R.id.menu_search);
searchView = (SearchView) MenuItemCompat.getActionView(searchViewBtn);
I am well aware by doing menu.clear() will keep refreshing the menu on switching Fragment.. But I don't know what to do to get the correct behavior..
Update menu_search.xml
<item
android:id="#+id/menu_search"
android:orderInCategory="200"
android:title="Search"
android:icon="#drawable/iconcariheader"
app:showAsAction="ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView"></item>
use my suggestion like this
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.menu_search:
searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener
(new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String query) {
// call your search function
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
// call your search function
return true;
}
});
break;
}
return super.onOptionsItemSelected(item);
}
Hope this will help and let me know for further.

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.

Categories

Resources