I have a custom FragmentPagerAdapter that im using to load two fragments to a ViewPager with corresponding tab titles in a TabLayout, however, only one fragment is being displayed when i run the code, but both fragment titles appear on the tab. At first, both fragments were not displaying, then i downgraded my gradle dependencies to v7 23.0.1 for both support:appcompat and support:design and my compile version to 23. After doing that, only one fragment is showing and the stacktrace is silent. Both fragments are ListFragments(from support library).
EDIT: First Fragment is appearing in second Fragment's position, and Second Fragment is not being displayed at all
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragments = new ArrayList<>();
private final List<String> fragmentTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager){super(manager);}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitles.get(position);
}
public void addFragment(Fragment fragment, String title){
fragments.add(fragment);
fragmentTitles.add(title);
}
}
TabbedActivity.java:
public class TabbedActivity extends AppCompatActivity {
Toolbar toolBar;
ViewPager viewPager;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
//Appearing in 2nd fragment position
adapter.addFragment(new FirstFragment(), "Frag 1");
//Not appearing
adapter.addFragment(new SecondFragment(), "Frag 2");
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
}
FirstFragment.java
public class FirstFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
SimpleCursorAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = {"_id", "name"};
int[] to = {R.id.lvtextViewTwo, R.id.lvtextViewOne};
adapter = new SimpleCursorAdapter(getActivity(), R.layout.list_view_layout, null, from, to, 0);
setListAdapter(adapter);
getActivity().getSupportLoaderManager().initLoader(0, null, this);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.first_fragment, container, false);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = DatabaseContentProvider.CUSTOMER_URI;
return new CursorLoader(getActivity(), uri, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
}
SecondFragment.java:
public class SecondFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>{
SimpleCursorAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = {"_id", "name"};
int[] to = {R.id.lvtextViewTwo, R.id.lvtextViewOne};
adapter = new SimpleCursorAdapter(getActivity(), R.layout.list_view_layout, null, from, to, 0);
setListAdapter(adapter);
getActivity().getSupportLoaderManager().initLoader(0, null, this);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.second_fragment, container, false);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = DatabaseContentProvider.ORDER_URI;
return new CursorLoader(getActivity(), uri, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
}
PS:New to SO, please let me know if I've left anything out.
Populate your List of Fragments inside FragmentPagerAdapter or pass pre-populated List through constructor to the adapter
public ViewPagerAdapter(FragmentManager manager)
{
super(manager);
//Title 'Frag 1' shows, but not actual fragment
addFragment(new FirstFragment(), "Frag 1");
//Both title and fragment show
addFragment(new SecondFragment(), "Frag 2");
}
OR
public ViewPagerAdapter(FragmentManager manager, List<Fragment> fragments)
{
super(manager);
this.fragments = fragments;
}
I discovered the problem was calling getActivity().getSupportLoaderManager().initLoader(0, null, this); with the same ID(0) from both Fragments. Solution was to give each initLoader call a unique ID.
Related
I am trying to add tabs in a Fragment (for a bottom navigation bar). However, when I run the app, the tabs don't show up at all. Below is an image of the result:
IMAGE
Home.java -> the fragment that should display 2 tabs which includes BlankFragment.java
CategoryAdapater.java -> sets up the tab names and fragments to display in each tab
BlankFragment.java -> an empty fragment that is shown on each tab
How can I get it to work?
Home.java (the fragment that should show the tabs)
public class Home extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
ViewPager viewPager = rootView.findViewById(R.id.viewpager);
CategoryAdapter adapter = new CategoryAdapter(getChildFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
public Home() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
CategoryAdapater.java
public class CategoryAdapter extends FragmentPagerAdapter {
public CategoryAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new BlankFragment();
} else {
return new BlankFragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Devices";
} else {
return "Numbers";
}
}
}
BlankFragment.java
public class BlankFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
return rootView;
}
public BlankFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
adapter addFragment missing
ViewPager viewPager = rootView.findViewById(R.id.viewpager);
CategoryAdapter adapter = new CategoryAdapter(getChildFragmentManager());
BlankFragment frag= new BlankFragment ();
adapter.addFragment(frag);
viewPager.setAdapter(adapter);
TabLayout tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
public class Home extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
ViewPager viewPager = rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
CategoryAdapter adapter = new CategoryAdapter(getChildFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
public Home() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new
ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Devices");
adapter.addFragment(new TwoFragment(), "Numbers");
viewPager.setAdapter(adapter);
}
#Override
public void onDetach() {
super.onDetach();
}
}
Update Home Class with this code
I have a variable in MainActivity that I have successfully passed to StoriesActivity.
The problem is with getting it from there to StoriesFragment, which is a TabLayout tab.
I understand about Intents and Bundles but I'm not sure how they'd work in this instance.
This is StoriesActivity:
public class StoriesActivity extends AppCompatActivity {
//This is our tablayout
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stories);
/* +++ START Intent +++ */
Bundle extras = getIntent().getExtras();
final int authorID = extras.getInt("author_id");
final String authorName = extras.getString("author_name");
Log.i("click", Integer.toString(authorID));
// this is successful
/* +++ END Intent +++ */
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(authorName);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new StoriesFragment(), "Stories");
adapter.addFragment(new CollectionsFragment(), "Collections");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
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);
}
}
}
And this is StoriesFragment (which doesn't work at the moment because it's not accessing the authorID variable from StoriesActivity):
public class StoriesFragment extends Fragment {
public StoriesFragment() {
// Required empty public constructor
}
private ListView storiesListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// link ListView object with XML ListView
storiesListView = (ListView) findViewById(R.id.stories_list_view);
// create new instance of DatabaseHelper
DatabaseHelper db = new DatabaseHelper(this);
// create list of stories through getAllStories method
List<Book> storyList = db.getAllStories(authorID);
// create new ArrayAdapter
ArrayAdapter<Book> arrayAdapter =
new ArrayAdapter<Book>(this, android.R.layout.simple_list_item_1, storyList);
// link ListView and ArrayAdapter
storiesListView.setAdapter(arrayAdapter);
Log.i("test", storyList.toString());
storiesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Book story = (Book) storiesListView.getItemAtPosition(i);
//Log.i("click", story);
Intent intent = new Intent(StoriesActivity.this, StoryBodyActivity.class);
intent.putExtra("story", story.getTitle());
startActivity(intent);
//Log.i("click", "That's a click!");
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_stories, container, false);
}
}
StoriesTabsAdapter:
public class StoriesTabsAdapter extends FragmentPagerAdapter {
int mNumOfTabs;
public StoriesTabsAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
private String[] tabTitles = new String[]{"Stories", "Collections"};
// overriding getPageTitle()
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
StoriesFragment tab1 = new StoriesFragment();
return tab1;
case 1:
CollectionsFragment tab2 = new CollectionsFragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return tabTitles.length;
}
}
Here is solution to your problem:
This is your activity:
public class StoriesActivity extends AppCompatActivity {
//This is our tablayout
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
private Toolbar toolbar;
private int authorID;
private String authorName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stories);
/* +++ START Intent +++ */
Bundle extras = getIntent().getExtras();
authorID = extras.getInt("author_id");
authorName = extras.getString("author_name");
Log.i("click", Integer.toString(authorID));
// this is successful
/* +++ END Intent +++ */
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(authorName);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(StoriesFragment.newInstance(authorID, authorName), "Stories");
adapter.addFragment(new CollectionsFragment(), "Collections");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
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);
}
}
}
This is your fragment:
public class StoriesFragment extends Fragment {
private int authorID;
private String authorName;
public StoriesFragment() {
// Required empty public constructor
}
public static StoriesFragment newInstance(int authorID, String authorName) {
Bundle args = new Bundle();
args.putInt("author_id", authorID);
args.putString("author_name", authorName);
StoriesFragment fragment = new StoriesFragment();
fragment.setArguments(args);
return fragment;
}
private ListView storiesListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Here is your arguments
authorID = getArguments().getInt("author_id");
authorName = getArguments().getString("author_name");
// link ListView object with XML ListView
storiesListView = (ListView) findViewById(R.id.stories_list_view);
// create new instance of DatabaseHelper
DatabaseHelper db = new DatabaseHelper(this);
// create list of stories through getAllStories method
List<Book> storyList = db.getAllStories(authorID);
// create new ArrayAdapter
ArrayAdapter<Book> arrayAdapter =
new ArrayAdapter<Book>(this, android.R.layout.simple_list_item_1, storyList);
// link ListView and ArrayAdapter
storiesListView.setAdapter(arrayAdapter);
Log.i("test", storyList.toString());
storiesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Book story = (Book) storiesListView.getItemAtPosition(i);
//Log.i("click", story);
Intent intent = new Intent(StoriesActivity.this, StoryBodyActivity.class);
intent.putExtra("story", story.getTitle());
startActivity(intent);
//Log.i("click", "That's a click!");
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_stories, container, false);
}
}
Hope it will help you.
for sending bundle data from your StoriesActivity
private void setupViewPager(ViewPager viewPager) {
Bundle bundle = new Bundle();
bundle.putString("your_key", "yourdata");
// set Fragmentclass Arguments
StoriesFragment fragStory = new StoriesFragment();
fragStory.setArguments(bundle);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(fragStory, "Stories");
adapter.addFragment(new CollectionsFragment(), "Collections");
viewPager.setAdapter(adapter);
}
i have a Fragment(C) with a ViewPager(Adapter) with 2 Fragments(A/B).
When i call the Fragment once time, they load fine.
But when i call the Fragment(C) the secend time, the Fragment A and B dont call the View onCreateView methode and the isnĀ“t loaded.
The Fragment C is called with Fragmetnmanger:
FragmentC fragment = new FragmentC();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.adressenmdf_detail_container, fragment).addToBackStack(null).commit();
Fragment C
public BelegeDetails(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_belege_details, container, false);
//TODO Actionbar noch anpassen
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
The Setups from Fragment C
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(this.getFragmentManager());
adapter.addFragment(new BelegeDetails1(),"Details" );
adapter.addFragment(new BelegeDetailsPos(), "Positionen");
viewPager.setAdapter(adapter);
}
private void setupTabIcons() {
tabLayout.getTabAt(1).setIcon(R.drawable.ic_belege);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
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);
}
}
The Fragment A BelegDetails1 und the Fragment B BelegDetailsPos are normal Fragment Classes like:
public BelegeDetails1() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState.......
try changing this:
ViewPagerAdapter adapter = new ViewPagerAdapter(this.getFragmentManager());
with:
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
As you are nesting fragments, you need to use getChildFragmentManager() instead of getFragmentManager()
I am having a rather annoying problem using tabs in android. I am not sure how they work, problem I am having is knowing where to put the logic of my code. say for example on the first tab I wanted to apply a calendar and the second tab upload a file, for example where would I put this logic, I have 3 xml fragments and so far I have been trying to code the logic by the onCreateView. If anyone could explain how tabbed activities work I would be eternally grateful I used the default android set up for a tabbed activity and added 3 fragments.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {
View rootView = inflater.inflate(R.layout.fragment_message, container, false);
return rootView;
}
else if(getArguments().getInt(ARG_SECTION_NUMBER)==2){
View rootView = inflater.inflate(R.layout.fragment_read, container, false);
TextView textView= (TextView)rootView.findViewById(R.id.textView_two);
textView.setText("Working");
return rootView;
}
else{
View rootView = inflater.inflate(R.layout.fragment_calendar, container, false);
// would I put my logic here?
return rootView;
}
}
}
Update 2
So now I am trying to listen for button presses and show a toast on one of the fragments,the button does not respond and the Toasts do not appear.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView=inflater.inflate(R.layout.fragment_calendar, container, false);
//final ActionBar actionBar = getSupportActionBar();
//actionBar.setDisplayHomeAsUpEnabled(false);
//actionBar.setTitle(null);
//Toast.makeText(getActivity(),"AKHBKH",Toast.LENGTH_LONG).show();
Button button1=(Button)rootView.findViewById(R.id.button_test1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("","");
Toast.makeText(getActivity(),"ddfdf",Toast.LENGTH_LONG).show();
}
});
PS I have tried all these on the Toast
getActivity()
getActivity().getApplicationContext()
getBaseContext()
getContext()
You can take three fragments and All the logic you want to implement should be in each of the fragment respectively. Take MainActivity to View all the fragments. Here i'll share my piece of code.
MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Admin(), "ADMIN");
adapter.addFragment(new Faculty(), "FACULTY");
adapter.addFragment(new Student(), "STUDENT");
viewPager.setAdapter(adapter);
}
//----------------------------------------------------------------------------------------------
class ViewPagerAdapter extends FragmentPagerAdapter {
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 void onBackPressed(){
//Do Here what ever you want do on back press;
}
}
I'll share the code of any one of the fragments: Admin
public class Admin extends Fragment {
EditText aid;
EditText apassword;
Button submit1,changepass;
String id = null, pass = null;
String table = null;
public Admin() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView=inflater.inflate(R.layout.fragment_admin, container, false);
aid=(EditText)rootView.findViewById(R.id.admin_id);
apassword=(EditText)rootView.findViewById(R.id.admin_password);
changepass=(Button)rootView.findViewById(R.id.changePass);
submit1=(Button)rootView.findViewById(R.id.submit1);
submit1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submit1();
}
});
changepass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in=new Intent(getActivity(),ChangePassword.class);
startActivity(in);
}
});
// Inflate the layout for this fragment
return rootView;
}
//For Admin login Authentication
public void submit1() {
id = aid.getText().toString();
pass = apassword.getText().toString();
Log.d("id", id);
Log.d("pass", pass);
table="admin";
// new ExecuteTask().execute(id, pass, table);
}}
Initially create an activity MainActivity.
You must create 3 fragments.Extend your activity from FragmentActivity and also implement ActionBar.TabListener
Refer this tutorial:
http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/
I have three tabs using the implementation below and they perform very well. When tab is changed the proper fragment is load and so on. The problem is that, when i get to the last tab and comeback to the first fragment, its like its oncreateview method is always triggered again running the other codes it in causing duplicates. Any help will be greatly appreciated.
//Activity on the tab is based
public class Dashboard extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private int[] tabIcon = {R.drawable.ic_home, R.drawable.ic_message, R.drawable.ic_person};
android.support.v7.widget.Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
//Toolbar
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//ViewPager
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
//Tablayout
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(tabIcon[0]);
tabLayout.getTabAt(1).setIcon(tabIcon[1]);
tabLayout.getTabAt(2).setIcon(tabIcon[2]);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch(tab.getPosition()) {
case 0:
viewPager.setCurrentItem(0);
toolbar.setTitle("Home");
break;
case 1:
viewPager.setCurrentItem(1);
toolbar.setTitle("Messages");
break;
case 2:
viewPager.setCurrentItem(2);
toolbar.setTitle("Profile");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager){
myViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
myViewPagerAdapter.addFragments(new CategoryFragment(), "Categories");
myViewPagerAdapter.addFragments(new MessagesFragment(), "Messages");
myViewPagerAdapter.addFragments(new ProfileFragment(), "Profile");
viewPager.setAdapter(myViewPagerAdapter);
}
//View Pager Adapter
public class MyViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragments(Fragment fragments, String titles){
this.fragments.add(fragments);
this.tabTitles.add(titles);
}
public MyViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
//return tabTitles.get(position);
return null;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
//Main first fragment code
public class CategoryFragment extends Fragment {
private DBHandler dbHandler;
private ListView listView;
private ListAdapter adapter;
ArrayList<Categories> categoriesList = new ArrayList<Categories>();
public CategoryFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
//Setting up the basic categories
dbHandler = new DBHandler(view.getContext());
//Get Categories from database
final Cursor cursor = dbHandler.getCategories(0);
if (cursor != null) {
if(cursor.moveToFirst()){
do{
Categories categories = new Categories();
categories.set_id(cursor.getInt(0));
categories.set_categoryname(cursor.getString(2));
categories.set_categoriescaption(cursor.getString(3));
categoriesList.add(categories);
}while (cursor.moveToNext());
}
cursor.close();
}
listView = (ListView) view.findViewById(R.id.categories);
adapter = new CategoryAdapter(view.getContext(), R.layout.cursor_row, categoriesList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Integer cid = (int) (long) adapter.getItemId(position);
TextView categoryname = (TextView) view.findViewById(R.id.cursor);
String cname = categoryname.getText().toString();
Intent i = new Intent(view.getContext(), CategoryList.class);
i.putExtra("categoryname", cname);
i.putExtra("categoryid", cid);
startActivity(i);
}
}
);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
So when i swipe back here from the last tab. OncreateView runs again. How can i handle that and prevent duplicates. Thank you
By defaults ViewPager retains only 1 page in the view hierarchy in an idle state.So when you swipe to third tab the viepager destroys the first tab in order to retain the second one.
To solve this issue add this line
viewPager.setOffscreenPageLimit(3);
after you set your adapter.
Check here the documentation for more