I am using a viewpager "tabs + swipe" and I would like to set different titles in the actionBar for each fragment so that when I switch, title changes.
I tried several things without success, only the last title displays... and does not change anymore when I switch...
First, make your activity implement an OnPageChangeListener.
Then, when you create your ViewPager, you can use mViewPager.setOnPageChangeListener(this) so that your activity will receive callbacks when the page changes.
Finally, you need to implement the OnPageChangeListener callbacks. Your onPageSelected() method should be something like this:
#Override
public abstract void onPageSelected(int position) {
setTitle(getTitleFromPosition(position));
}
The other two callbacks can be empty.
Though the question is a bit outdated I would suggest my solution. Scenario: tabs+swipe and every tab have fragment navigation stack. So action bar title can be changed not only through switching and swiping tabs but with navigation in every tab. To provide title per fragment I declared TitleProvider interface, so if fragment has custom title it must implement this interface.
public interface TitleProvider {
CharSequence getTitle();
}
Below there is custom FragmentPagerAdapter, that handles switching, swiping, navigation and title update:
public class TabsAdapter extends FragmentPagerAdapter implements
TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final FragmentActivity activity;
private final TabHost tabHost;
private final ViewPager viewPager;
private final ArrayList<Fragment> fragments = new ArrayList<Fragment>();
private final Hashtable<Fragment, Stack<Class<?>>> fragmentBackstack = new Hashtable<Fragment, Stack<Class<?>>>();
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context context;
public DummyTabFactory(Context context) {
this.context = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(context);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapter(FragmentActivity activity, TabHost tabHost,
ViewPager pager) {
super(activity.getSupportFragmentManager());
this.activity = activity;
this.tabHost = tabHost;
viewPager = pager;
tabHost.setOnTabChangedListener(this);
viewPager.setAdapter(this);
viewPager.setOnPageChangeListener(this);
}
public void addTab(String tag, int drawableId, Fragment fragment,
int tabIndicatorId) {
TabSpec tabSpec = tabHost.newTabSpec(tag);
tabSpec.setContent(new DummyTabFactory(activity.getApplicationContext()));
View tabIndicator = LayoutInflater.from(
activity.getApplicationContext()).inflate(tabIndicatorId,
tabHost.getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.tab_title);
if (fragment instanceof TitleProvider) {
title.setText(((TitleProvider) fragment).getTitle());
}
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.tab_icon);
icon.setImageResource(drawableId);
tabSpec.setIndicator(tabIndicator);
fragments.add(fragment);
tabHost.addTab(tabSpec);
notifyDataSetChanged();
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getItemPosition(Object object) {
int returnCode;
if (fragments.contains(object)) {
returnCode = POSITION_UNCHANGED;
} else {
returnCode = POSITION_NONE;
}
return returnCode;
}
#Override
public void onTabChanged(String tabId) {
int position = tabHost.getCurrentTab();
viewPager.setCurrentItem(position);
updateTitle();
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// Unfortunately when TabHost changes the current tab, it kindly
// also takes care of putting focus on it when not in touch mode.
// The jerk.
// This hack tries to prevent this from pulling focus out of our
// ViewPager.
TabWidget widget = tabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
tabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
}
#Override
public void onPageScrollStateChanged(int state) {
}
public void navigate(Fragment fromFragment, Fragment toFragment) {
startUpdate(viewPager);
FragmentTransaction transaction = activity.getSupportFragmentManager()
.beginTransaction();
transaction.remove(fromFragment);
transaction.commit();
Stack<Class<?>> backstack;
if (fragmentBackstack.containsKey(fromFragment)) {
backstack = fragmentBackstack.get(fromFragment);
fragmentBackstack.remove(fromFragment);
} else {
backstack = new Stack<Class<?>>();
}
backstack.push(fromFragment.getClass());
fragmentBackstack.put(toFragment, backstack);
fragments.set(fragments.indexOf(fromFragment), toFragment);
finishUpdate(viewPager);
notifyDataSetChanged();
updateTitle();
}
public Boolean navigateBack() {
startUpdate(viewPager);
Fragment fromFragment = fragments.get(viewPager.getCurrentItem());
if (!fragmentBackstack.containsKey(fromFragment))
return false;
Stack<Class<?>> backstack = fragmentBackstack.get(fromFragment);
if (backstack.isEmpty())
return false;
fragmentBackstack.remove(fromFragment);
Fragment toFragment = Fragment.instantiate(activity, backstack.pop()
.getName());
fragmentBackstack.put(toFragment, backstack);
fragments.set(fragments.indexOf(fromFragment), toFragment);
FragmentTransaction transaction = activity.getSupportFragmentManager()
.beginTransaction();
transaction.remove(fromFragment);
transaction.commit();
finishUpdate(viewPager);
notifyDataSetChanged();
updateTitle();
return true;
}
protected Fragment getCurrentFragment() {
return fragments.get(viewPager.getCurrentItem());
}
protected void updateTitle() {
Fragment fragment = getCurrentFragment();
if (fragment instanceof TitleProvider) {
activity.setTitle(((TitleProvider) fragment).getTitle());
}
}
}
#Override
public void onPageSelected(int position) {
tabHost.setSelectedNavigationItem(position);
if (position == 0){
setTitle(R.string.where_is_the_bus);
}
else if (position == 1){
setTitle(R.string.bus_card);
}
else if (position == 2){
setTitle(R.string.favo);
}
You can make it like this "it's easy right?"
Related
I have 3 tab fragments in viewpager with tabs. All tabs have recyclerview with ListAdapter showing customers list. Each tab represents 1) all customers 2) New ordered customers 3) Paid customers. I want to set search filter only on tab selected fragment. If the Searchview can place on activity which is common for all fragments, will be better in my case. I tried several ways but was failed. My search was resulting always only in last tab (Paid). Please can any one help me with full example of code ?
And my MainActivity
private void initializeTab(){
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager = (MyViewPager) findViewById(R.id.view_pager);
viewPager.setOffscreenPageLimit(5);
viewPager.setAdapter(mSectionsPagerAdapter);
tabLayout = (SmartTabLayout) findViewById(R.id.tabs);
tabLayout.setViewPager(viewPager);
viewPager.setPagingEnabled(true);
}
private class SectionsPagerAdapter extends FragmentStatePagerAdapter {
protected int currentPosition = -1;
protected Fragment currentFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
#Override
public Fragment getItem(int position) {
return ViewPagerFragment.newInstance(getPageTitle(position)+"");
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "All";
case 1:
return "New";
case 2:
return "Paid";
}
return null;
}
#Override
public void setPrimaryItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
super.setPrimaryItem(container, position, object);
this.currentPosition = position;
if (object instanceof Fragment){
this.currentFragment = (Fragment)object;
}
}
public Fragment getCurrentFragment() {
return currentFragment;
}
public void setCurrentFragment(Fragment currentFragment) {
this.currentFragment = currentFragment;
}
}
and my Fragment
public class ViewPagerFragment extends AbstractFragment {
............
public static ViewPagerFragment newInstance(String title) {
ViewPagerFragment fragment = new ViewPagerFragment();
Bundle args = new Bundle();
args.putString("TITLE",title);
fragment.setArguments(args);
return fragment;
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeToRefresh);
recycler = (RecyclerView) view.findViewById(R.id.recycler);
adapter = new CustomerAdapter(getContext());
recycler.setLayoutManager(new LinearLayoutManager(getContext()));
recycler.setHasFixedSize(true);
recycler.addItemDecoration(new ItemDecoration(1,false, dpToPx(0),true,2));
recycler.setItemAnimator(new DefaultItemAnimator());
recycler.setAdapter(adapter);
changeFragment(swipeLayout);
}
public void changeFragment(final SwipeRefreshLayout swipeLayout){
final String tab = getArguments().getString("TITLE");
loadDatas(allRecords,tab);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeLayout.setRefreshing(true);
utils.getDetails(getContext());
utils.setOnDataLoaded(new MyUtils.DataLoadingListener() {
#Override
public void onDataLoaded(ArrayList<Customers> list) {
loadDatas(list, tab);
swipeLayout.setRefreshing(false);
}
});
}
});
// Scheme colors for animation
swipeLayout.setColorSchemeColors(
getResources().getColor(android.R.color.holo_blue_bright),
getResources().getColor(android.R.color.holo_green_light),
getResources().getColor(android.R.color.holo_orange_light),
getResources().getColor(android.R.color.holo_red_light)
);
}
void loadDatas(List<Customers> list, String tab){
if (list != null && list.size() > 0) {
List<Customers> tabList = new ArrayList<>();
if (tab.equals("All")) {
tabList = list;
}else {
for (Customers item : list) {
if (item.getStatus().equals(tab)) {
tabList.add(item);
}else {
Log.d(TAG, "loadDatas: "+item.getStatus());
}
}
}
adapter.submitList(tabList);
}
}
}
the Searchview can place on activity which is common for all fragments, will be better in my case.
This is right.
I tried several ways but was failed. My search was resulting always only in last tab (Paid).
So, I'm assuming that the issue now isn't in the filtering itself, but that it always returns the results of the last tab; and therefore you probably didn't provide the filtering code for such a reason.
Now we've 3 tabs in the ViewPager, each represents a fragment; So we need to get the current selected fragment of the ViewPager in order to allow the activity send it the searched text.
To get the current fragment from ViewPager (Your case):
ViewPagerFragment currentFragment = (ViewPagerFragment) mViewPagerAdapter.instantiateItem(viewPager, viewPager.getCurrentItem());
To get the current fragment from ViewPager2:
The ViewPager has getCurrentItem() which returns the current page number
So, we need to link the each page fragment to the page number.
But we can get a ViewPager fragment by its id (item id), so the first step is to have page Ids that equals to the corresponding position, to do so override getItemId in the ViewPager adapter.
#Override
public long getItemId(int position) {
return position;
}
Then in the activity filtering part assuming you are searching for a String that is in a var named seachString:
int pageId = viewpager.getCurrentItem();
Fragment currentFragment = (ViewPagerFragment) getChildFragmentManager()
.findFragmentByTag("f" + pageId);
Then after getting the current fragment, create some method in it that accepts a String parameter for the searched value:
So, in ViewPagerFragment, create:
public void searchFor(String search) {
// filter the results of the RecyclerView
}
And call that method on the current fragment of the ViewPager in the activity:
currentFragment.searchFor(seachString);
About the recyclerview filter data:
could make your class CustomerAdapter implements Filterable
like :
class Adapter extends RecyclerView.Adapter implements Filterable {
......
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
return ...;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
}
};
}
}
could also refer this:https://github.com/xaverkapeller/Searchable-RecyclerView-Demo
About how to do this in selected viewpager fragment , you just need to invoke the search method of the current fragment.
At last I succeeded, I think it is not very professional but it is working fine. To help some one suffering I am sharing that here.
Firstly I added tabScrollingListener to get the selected fragment in MainActivity
public class MainActivity extends AppCompatActivity{
..........
private ViewPagerFragment selectedFragment;
private void initializeTab(){
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager = (MyViewPager) findViewById(R.id.view_pager);
viewPager.setOffscreenPageLimit(5);
viewPager.setAdapter(mSectionsPagerAdapter);
tabLayout = (SmartTabLayout) findViewById(R.id.tabs);
tabLayout.setViewPager(viewPager);
viewPager.setPagingEnabled(true);
viewPager.setCurrentItem(0);
tabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
selectedFragment = (ViewPagerFragment) mSectionsPagerAdapter.getCurrentFragment();
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
Then I transferred my filter function to Fragment like mentioned in Zain's answer. As I am using ListAdapter for my recycler it's easy to submit my filter list to adapter. I loaded my filter list on loadData function.
public class ViewPagerFragment extends AbstractFragment {
............
private List<Customers> filterList;
public static ViewPagerFragment newInstance(String title) {
ViewPagerFragment fragment = new ViewPagerFragment();
Bundle args = new Bundle();
args.putString("TITLE",title);
fragment.setArguments(args);
return fragment;
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeToRefresh);
recycler = (RecyclerView) view.findViewById(R.id.recycler);
adapter = new CustomerAdapter(getContext());
recycler.setLayoutManager(new LinearLayoutManager(getContext()));
recycler.setHasFixedSize(true);
recycler.addItemDecoration(new ItemDecoration(1,false, dpToPx(0),true,2));
recycler.setItemAnimator(new DefaultItemAnimator());
recycler.setAdapter(adapter);
changeFragment(swipeLayout);
}
public void changeFragment(final SwipeRefreshLayout swipeLayout){
final String tab = getArguments().getString("TITLE");
loadDatas(allRecords,tab);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeLayout.setRefreshing(true);
utils.getDetails(getContext());
utils.setOnDataLoaded(new MyUtils.DataLoadingListener() {
#Override
public void onDataLoaded(ArrayList<Customers> list) {
loadDatas(list, tab);
swipeLayout.setRefreshing(false);
}
});
}
});
// Scheme colors for animation
swipeLayout.setColorSchemeColors(
getResources().getColor(android.R.color.holo_blue_bright),
getResources().getColor(android.R.color.holo_green_light),
getResources().getColor(android.R.color.holo_orange_light),
getResources().getColor(android.R.color.holo_red_light)
);
}
void loadDatas(List<Customers> list, String tab){
if (list != null && list.size() > 0) {
List<Customers> tabList = new ArrayList<>();
if (tab.equals("All")) {
tabList = list;
}else {
for (Customers item : list) {
if (item.getStatus().equals(tab)) {
tabList.add(item);
}else {
Log.d(TAG, "loadDatas: "+item.getStatus());
}
}
}
filterList = tabList; // this fills filter list
adapter.submitList(tabList);
}
}
}
public void filter(String text, String filter) {
ArrayList<Customers> filteredlist = new ArrayList<>();
// running a for loop to compare elements.
if (filterList != null && filterList.size() > 0) {
if (text.length() > 0) {
for (Customers item : filterList) {
// here filter options gone
}
}else {
filteredlist.addAll(filterList);
}
}
adapter.submitList(filteredlist);
}
Yea, Now I got currentSelectedFragment with filter function in MainActivity
In searchListener I can call it like selectedFragment.filter(query).
searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
selectedFragment.filter(newText); // search filter here
return true;
}
});
Follow the below step to find the clicked tab,
First add tab select listener
tabLayout.addOnTabSelectedListener(object:TabLayout.OnTabSelectedListener{
override fun onTabSelected(tab: TabLayout.Tab?) {
selectedFragment= fragmentViewPagerAdapter!!.fragments[tab!!.position]
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
// enter code here
}
override fun onTabReselected(tab: TabLayout.Tab?) {
// enter code here
}
})
and then setupWithViewPager
tabLayout.setupWithViewPager(viewPager)
so i got one main activity that has a Tablayout and a ViewPager to present diffrent fragments.
when i move between the fragments with my Tablayout everything works good, but if i use a button to open fragment, when going back to the former fragment (by pushing the cancel button) the elements of the fragment i left staying on the screen (as in the picture).
i tried to use a method viewPager.setCurrentItem(0); in the fragment to go back to the homepage from the fragment instade of ft.replace(R.id.fragment_edit_reminder, new Main_Activity_fragment()).commit(); but it didn't moved back to my home fragment (with the repalce it does go back but as i saied the elements.
this is my main:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TabLayout tableLayout = findViewById(R.id.Tablayouting);
final ViewPager viewPager = findViewById(R.id.ViewPager);
PagerAdapter pagerAdapter = new
PagerAdapter(getSupportFragmentManager(),tableLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
tableLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
this is the fragment:
public class edit_reminder_fragment extends Fragment implements View.OnClickListener {
private Button cancelButton;
public edit_reminder_fragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment edit_reminder_fragment.
*/
public static edit_reminder_fragment newInstance() {
edit_reminder_fragment fragment = new edit_reminder_fragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void onClick(View view)//TODO: make a utility method for switching fragments on the main_activity_fragment(see note).
{
switch (view.getId()) {//recognizing what button was pushed
case R.id.ButtonCancelReminder:
//region
FragmentTransaction ft = getFragmentManager().beginTransaction();
Main_Activity_fragment maf = new Main_Activity_fragment();
ft.replace(R.id.fragment_edit_reminder, maf).commit();
break;
//endregion
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_reminder_fragment, container, false);
cancelButton = view.findViewById(R.id.ButtonCancelReminder);
cancelButton.setOnClickListener(this);
return view;
}
}
my pagerAdapted class:
public class PagerAdapter extends FragmentPagerAdapter {
//https://www.youtube.com/watch?v=HHd-Fa3DCng&ab_channel=MasterCoding
private int numOfTabs;
public PagerAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Main_Activity_fragment();
case 1:
return new key_words_fragment();
case 2:
return new groups_and_points_fragment();
case 3:
return new Fragment_Past_Reminders();
case 4:
return new edit_reminder_fragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
in the picture we see the home page fragment ,on it 3 buttons (cancel, save, Add a sub reminder) that stayed from a fragment that open when clicking on the ADD NEW REMINDER button (when clicking on cancel in the second fragment it's going back to the home page):
First, try the following as an adaper:
public class PagerAdapter extends
FragmentPagerAdapter {
private final ArrayList<Fragment> mFragments = new ArrayList<>();
private final ArrayList<String> mFragmentTitle = new ArrayList<>();
public PagerAdapter(FragmentManager mManager) {
super(mManager);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitle.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitle.get(position);
}
public Fragment getFragment(int position) {
if (position < mFragments.size() && position >= 0) {
return mFragments.get(position);
}
return null;
}
}
Then in your MainActivity's onCreate, initialize the following:
mTabs = (TabLayout) findViewById(R.id.tabs);
mPager = (ViewPager) findViewById(R.id.view_pager);
mMainAdapter = new PagerAdapter( getSupportFragmentManager() );
setupContents();
Then the private method setupContents() as follows:
mMainAdapter.addFragment(new FragmentOne(), getResources().getString(R.string.tab_albums));
mMainAdapter.addFragment(new FragmentTwo(), getResources().getString(R.string.tab_songs));
mMainAdapter.addFragment(new FragmentThree(), getResources().getString(R.string.tab_playlists));
// you can add as many fragments as you wish
//just follow the previous method #mMainAdapter.addFragment
mPager.setAdapter(mMainAdapter);
mTabs.setupWithViewPager(mPager);
To get the current fragment:
public Fragment getCurrentFragment() {
return mMainAdapter.getFragment(mPager.getCurrentItem());
}
To check if the current fragment is FragmentOne:
private boolean isFragmentOne() {
return getCurrentFragment() instanceof FragmentOne;
}
My app creates drawer submenus from sharedpreference values. These submenus are basically called "interests" or categories. I'm trying to move this same functionality to tablayout since that is much more convenient but can't seem to get it to work!
Edit: New code based on suggestions.
TabsFragment:
public class HomeTabsFragment extends Fragment implements ViewPager.OnPageChangeListener {
private View view;
private SectionsPagerAdapterHome homePageAdapter;
public ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.view = inflater.inflate(R.layout.fragment_articles_tabs, container, false);
TabLayout tabLayout = view.findViewById(R.id.home_list_tabs);
viewPager = view.findViewById(R.id.home_list_tabs_container);
homePageAdapter = new SectionsPagerAdapterHome(getFragmentManager());
viewPager.setAdapter(homePageAdapter);
viewPager.setOffscreenPageLimit(tabLayout.getTabCount());
viewPager.addOnPageChangeListener(this);
tabLayout.setupWithViewPager(viewPager);
if(SharedPrefernces.getUserInterests()!=null) {
List<String> my_interests = SharedPrefernces.getUserInterests();
Collections.sort(my_interests, String::compareToIgnoreCase);
my_interests.add(0, getString(R.string.all_stories));
for (String interest : my_interests) {
homePageAdapter.addTabPage(new FeedsFragment(), interest);
}
}
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment fragment = homePageAdapter.getFragment(position);
if (fragment != null) {
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
Adapter:
public class SectionsPagerAdapterHome extends FragmentPagerAdapter {
private FragmentManager fragmentManager;
private ArrayList fragmentTags = new ArrayList();
private ArrayList<String> titles = new ArrayList();
protected SectionsPagerAdapterHome(FragmentManager fm) {
super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
fragmentManager = fm;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object object = super.instantiateItem(container, position);
if (object instanceof Fragment) {
Fragment fragment = (Fragment) object;
String tag = fragment.getTag();
fragmentTags.add(position, tag);
}
return object;
}
public Fragment getFragment(int position) {
Fragment fragment = null;
Object tag = fragmentTags.get(position);
if (tag != null) {
fragment = fragmentManager.findFragmentByTag(String.valueOf(tag));
}
return fragment;
}
#Override
public Fragment getItem(int position) {
return FeedsFragment.newInstance();
}
public void addTabPage(Fragment fragment,String title) {
titles.add(title);
fragmentTags.add(fragment);
notifyDataSetChanged();
}
#Override
public int getCount() {
return fragmentTags.size();
}
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
I'm not sure how I can achieve this so need help.
Since you are using a ViewPager with an Adapter instead of using tabLayout.addTab(...) you have to add the item in the adapter.
Something like:
public class SectionsPagerAdapterHome extends FragmentPagerAdapter {
private ArrayList fragmentTags = new ArrayList();
private ArrayList<String> titles = new ArrayList();
//.....
public void addTabPage(Fragment fragment,String title) {
titles.add(title);
fragmentTags.add(fragment);
notifyDataSetChanged();
}
#Override
public int getCount() {
return fragmentTags.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tables.get(position);
}
}
I'm new to Android programming and am trying to figure out how to go about this. I have a fragment that hosts inner tabs, one of them being a ListFragment. On the tabhost fragment I have a button that calls a DialogFragment. When "Yes" is clicked on that DialogFragment I need to refresh that ListFragment if it's currently active in order to show the item added onto the list.
What is the best way to go about this? I am thinking I should put an interface on the DialogFragment and then implement the listener on the Activity which would then call the refresh in the ListFragment. I would need to be able to pull the ListFragment's tag in order to determine if it's active, however and not sure how to do that.
I just started to learn programming a few months ago and this is my first post on this site. I searched for this answer and couldn't find anything. I apologize if my methods or formatting are wrong. Any tips are appreciated, thanks.
TabFragment:
public class Items extends Fragment implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener, View.OnClickListener {
MyPageAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
static final String ARG_ID = "id";
static final String name = "name";
long id;
String itemName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.tab_test);
Bundle args = getArguments();
long id = args.getLong(ARG_ID);
String itemName = args.getString(name);
View v = inflater.inflate(R.layout.item_tab, container, false);
mViewPager = (ViewPager) v.findViewById(R.id.pager);
// Tab Initialization
//initialiseTabHost
mTabHost = (TabHost) v.findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
List<Fragment> fragments = getFragments();
FragmentActivity context = getActivity();
this.AddTab(context, this.mTabHost, this.mTabHost.newTabSpec("ItemList").setIndicator("ItemList"));
mTabHost.setOnTabChangedListener(this);
// Fragments and ViewPager Initialization
pageAdapter = new MyPageAdapter(getChildFragmentManager(), fragments);
mViewPager.setAdapter(pageAdapter);
mViewPager.setOnPageChangeListener(this);
if (savedInstanceState == null) {
}else {
int pos = savedInstanceState.getInt("tab");
mTabHost.setCurrentTab(pos);
}
Button addItemButton = (Button) v.findViewById(R.id.addItem);
addItemButton.setOnClickListener(this);
return v;
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.addItem:
DialogFragment addItem = new AddItemDialogFragment();
Bundle itemArgs = getArguments();
addItem.setArguments(itemArgs);
addItem.show(getChildFragmentManager(), "addItem");
Toast.makeText(getActivity(), "Adding Item", Toast.LENGTH_LONG).show();
break;
}
}
// Method to add a TabHost
private static void AddTab(FragmentActivity activity, TabHost tabHost, FragmentTabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(activity));
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// TODO Put here your Fragments
Bundle args = getArguments();
long id = args.getLong("val");
ItemList f1 = ItemList.newinstance(id);
fList.add(f1);
return fList;
}
public class MyPageAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
}
ListFragment within Tab:
public class ItemList extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
String DATABASE_TABLE;
String Query;
String Order;
String name;
MainActivity home;
View view;
public static MyListAdapter mAdapter;
private static Cursor c;
static ItemList newinstance(long rowId) {
ItemList itemList = new ItemList();
// Supply val input as an argument.
Bundle args = new Bundle();
args.putLong("val", rowId);
//args.putString("name", itemName);
itemList.setArguments(args);
return itemList;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle args = getArguments();
int itemId= (int) args.getLong("val");
mAdapter = new MyListAdapter(getActivity(), R.layout.list_row, c, from, to);
setListAdapter(mAdapter);
setListShown(false);
getLoaderManager().initLoader(itemId, null, this);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// View progressBar = getView().findViewById(R.id.progressbar_loading);
// progressBar.setVisibility(View.VISIBLE);
return new RawCursorLoader(getActivity(), Query + Order);
}
// Called when a previously created loader has finished loading
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
//View progressBar = getView().findViewById(R.id.progressbar_loading);
// progressBar.setVisibility(View.GONE);
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
mAdapter.swapCursor(data);
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
// Called when a previously created loader is reset, making the data unavailable
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
}
Dialog:
public class AddItemDialogFragment extends DialogFragment {
UpdateItemListener mListener;
public interface UpdateItemsListener {
public void onItemAdded();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mListener = (UpdateItemListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement UpdateItemListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Add " + itemName + "?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
postItem(ItemId);
mListener.onItemAdded();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
I was able to figure it out, my brain just got stuck for a while.
The first problem was that I was using FragmentStatePagerAdapter which does not set tags when instantiating the fragments. I set it to this since FragmentPagerAdapter was being buggy and another thread recommending extending that class instead. I was able to get it working with FragmentPagerAdapter which sets a tag. I then call getTag() during the onAttach() method of the ItemList fragment and set the variable on the activity. I then have an interface on the AddItemDialogFragment when the item is added and a listener on the activity. The listener then calls:
ItemList itemList= (ItemList)
getSupportFragmentManager().findFragmentByTag("Items")
.getChildFragmentManager().findFragmentByTag("itemListTag");
if(itemList != null) {
itemList.listChange();
}
I have implemented Tab view as well as Horizontal swipe view(to change tabs) with Navigation mode as Lists for the application. I am using ActionBarSherlock & TabPageIndicator. I used fragments for reloading the contents after changing the tabs.
In drop down spinner, I have 2 items. These are getting selected whenever activity reloads or after hitting on Tabs.
But, if swipe is performed to select other tab, then onNavigationItemSelected(int position, long itemId) will not getting triggered in Gingerbread version :( We have tested it on Gingerbread 2.3.6, 2.3.3.
In logcat, I got this warning message "View:onTouchEvent:ViewFlags" is DISABLED
But, it works perfectly fine on ICS, Froyo, etc.
Your help would be greatly appreciated.
following is the code snippet:
public class MainPageActivity extends SherlockFragmentActivity implements
ActionBar.OnNavigationListener {
MenuItem menuItem;
EditText searchText;
public static Context mContext;
public static DataAdapter dataAdapter;
ArrayList<String> accountList;
public static List<View> currentViewBeingChanged = new ArrayList<View>();
public static LayoutInflater layoutInflater;
public static String checktab = "running", nameComp;
int isRefresh;
public static boolean isAutoRefresh = true;
public static ArrayList<String> listItems;
public static boolean check;
public static boolean isAtleastOnce = true, listToBeRefreshed = false;
public static ActionBar actionBar;
public static int itemPosition, listPosition;
public static FragmentManager fragmentManager;
InputMethodManager imm;
#Override
protected void onCreate(Bundle savedInstanceState) {
mContext = this;
layoutInflater = getLayoutInflater();
fragmentManager = getSupportFragmentManager();
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
Context context = getSupportActionBar().getThemedContext();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
android.R.layout.simple_spinner_dropdown_item);
adapter.clear();
for (int i = 0; i < ManageAccountLists.accountList.size(); i++) {
adapter.add(ManageAccountLists.accountList.get(i));
}
actionBar.setListNavigationCallbacks(adapter, this);
tabPagerFunction();
}
public void tabPagerFunction() {
FragmentPagerAdapter adapter = new GoogleMusicAdapter(
getSupportFragmentManager());
adapter.notifyDataSetChanged();
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
checktab = "running";
final TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(pager);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
System.out.println("Tab selected..................");
if (arg0 == 0) {
// Running tab is selected
indicator.setCurrentItem(arg0);
checktab = "running";
RunningInstancesActivity runningInstancesActivity = new RunningInstancesActivity();
runningInstancesActivity.callThread();
} else {
// Stopped tab is selected
indicator.setCurrentItem(arg0);
checktab = "stopped";
StoppedInstancesActivity stoppedInstancesActivity = new StoppedInstancesActivity();
stoppedInstancesActivity.callThread();
InstanceStatusUpdate.isOnPostExecute = false;
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
class GoogleMusicAdapter extends FragmentPagerAdapter {
private final String[] CONTENT = new String[] { "Running", "Stopped" };
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
notifyDataSetChanged();
}
#Override
public Fragment getItem(int position) {
switch (position) {
/** Running tab is selected */
case 0:
checktab = "stopped";
return RunningInstancesActivity.newInstance(0);
/** Stopped tab is selected */
case 1:
checktab = "running";
return StoppedInstancesActivity.newInstance(1);
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
public CharSequence getPageTitle(int position, int number) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
#Override
public int getCount() {
return CONTENT.length;
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
System.out.println("Navigation item selected");
// Performs fetching
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
System.out.println("Dispatch touvh event..");
return super.dispatchTouchEvent(ev);
}
}
Try doing this
dependencies {
compile "com.android.support:appcompat-v7:18.0.+"
}
and use support library instead.
As far as I remember there were some issues with updating the navigation list after swiping (in ABS). This is what I did to solve this issue and it works with Android 2.3.7 (ABS) as well as with Android 4.0 (native AB).
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (navigatioBarIsUsed) actionBar.setSelectedNavigationItem(position);
if (tabsAreUsed) actionBar.getTabAt(position).select();
}
});
Internally it reselects the page - that's not so nice - however that was the only solution I found.
Cheers
Use This code..
Inside Your Fragment Use this code.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
// TODO Auto-generated method stub
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
Activity activity = getActivity();
ActionBar actionBar = ((ActionBarActivity) activity)
.getSupportActionBar();
actionBar.setIcon(getResources().getDrawable(R.drawable.nearby));
}
}