Hi I am developing an app using tabs and I am using the same fragment (News fragment.java) to fetch information into list view from different URL upon tab selection but I have a problem when I run my app then it works correctly but upon tab position selection they sometimes show different Tab (URL) info into list view like on the first run my app shows case 1 info into listview instead of case 0 and on direct selection of last tab case 5, it shows case 4 info into listview. What I am missing here
MainActivity.java
ViewPager viewPager = null;
TabLayout tabLayout;
static String url;
private static final String Topics[] = {"Pakistan", "World", "Sports", "Business", "Entertainment", "Health"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
ViewpagerAadapters adapter = new ViewpagerAadapters(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
private class ViewpagerAadapters extends FragmentStatePagerAdapter {
int tabCount;
private ViewpagerAadapters(FragmentManager fm, int tabCount) {
super(fm);
this.tabCount= tabCount;
}
#Override
public Fragment getItem(int position) {
Log.i("Position", "Posotion: " + position);
switch (position) {
case 0:
url = "https://www.geo.tv/rss/1/1";
return new GeoNews();
case 1:
url = "https://www.geo.tv/rss/1/2";
return new GeoNews();
case 2:
url = "https://www.geo.tv/rss/1/4";
return new GeoNews();
case 3:
url = "https://www.geo.tv/rss/1/3";
return new GeoNews();
case 4:
url = "https://www.geo.tv/rss/1/5";
return new GeoNews();
case 5:
url = "https://www.geo.tv/rss/1/6";
return new GeoNews();
default:
return null;
}
}
#Override
public int getCount() {
return Topics.length;
}
#Override
public CharSequence getPageTitle(int position) {
return Topics[position];
}
}
}
News Fragment Listview.Java
ListView listView;
int positions;
ArrayList<NewsItem> newsItemList;
NewsAdapter adapter;
String World ;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.geonews, container, false);
listView = (ListView) view.findViewById(R.id.listview_news);
if (savedInstanceState == null){
}
else{
positions = savedInstanceState.getInt("position",0);
}
World = MainActivity.url;
newsItemList = new ArrayList<>();
Related
This question already has an answer here:
Android Viewpager inside of Viewpager not showing layout
(1 answer)
Closed last month.
I have a BottomNavigation bar in main activity. Which has 5 items.
Here is the getitem method for that bottomnavigation
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new ChatRoomPage();
case 1:
return new TopicPage();
case 2:
return new TopicPage();
case 3:
return new Leaderboard();
case 4:
return new Stats();
}
return new ChatRoomPage();
}
I have added TopicPage() for testing.
So topic page is a fragment with tab layout. And that fragment shows three other fragments using tab view.
TopicPage() in case 2 is working fine.
But in case 3 fragment TopicPage() is showing. It's also calling the three fragments in tab layout (Getting message in log). But not visible in ViewPager. And the underline on tablayout is not sliding from one tab to another tab with animaton. I have to slide it manually.
And,
When I add a single fragment like Stats() or Leaderboard() it works.
Screenshot
Topic Page onCreateview
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
v = inflater.inflate(R.layout.topic_page, container, false);
tabLayout = v.findViewById(R.id.tab);
pager = v.findViewById(R.id.pager);
pager.setOffscreenPageLimit(4);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
pager.setAdapter(new TopicPagerAdapter(getFragmentManager()));
tabLayout.setupWithViewPager(pager);
return v;
}
So I don't know why I am getting this problem...
Need Help :(
Override a method in TopicPage() fragment called setUserVisibilityHint()
and in that method after the return statement ...write
if(getActivity()!=null) { viewPager.setAdapter(....youradapter); } I think it will work. First initialize the adapter of viewPager then set the adapter.....Let me know if it works..
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(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) {
}
});
}
PagerAdapter For Fragment
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment3 tab3 = new TabFragment3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
FirstFragment
public class TabFragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_1, container, false);
}
}
I'm new at Android programming and I need your help. Please.
What I want to do.
I created listview, from listview I created OnItemClickListener to TabbedActivity.
Now I want for each listview item to show different text on TabbedActivity.
This is MainActivity:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.app_name));
listview = (ListView) findViewById(R.id.listview);
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.bolesti));
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
switch (i){
case 0:
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(MainActivity.this, TabbedActivity.class);
startActivity(intent1);
break;
}
}
});
listview.setAdapter(mAdapter);
}}
TabbedActivity:
public class TabbedActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
// 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_tabbed, 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 placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabbed, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* 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) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position){
case 0:
Tab1Opis tab1 = new Tab1Opis();
return tab1;
case 1:
Tab2Simptomi tab2 = new Tab2Simptomi();
return tab2;
case 2:
Tab3Uzroci tab3 = new Tab3Uzroci();
return tab3;
case 3:
Tab4Lijecenje tab4 = new Tab4Lijecenje();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Opis";
case 1:
return "Simptomi";
case 2:
return "Uzroci";
case 3:
return "Lijecenje";
}
return null;
}
}}
TabbedActivity contains 4 tabs, all of them have different .java class example:
public class Tab2Simptomi extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_simptomi, container, false);
return rootView;
}}
I need to change text in every fragment when I click on different listview item.
Can you help me? Thank you.
Check the pictures. Thank you a lot.
You can pass text from your MainActivity to TabbedActivity fragment Tab2Simptomi as below:
1. Pass text from MainActivity to TabbedActivity, using Intent extras.
Update onItemClick() as below:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
switch (i){
case 0:
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
intent.putExtra("YOUR_TEXT", "Text One");
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(MainActivity.this, TabbedActivity.class);
intent1.putExtra("YOUR_TEXT", "Text Two");
startActivity(intent1);
break;
}
}
});
2. Pass text from TabbedActivity to Tab2Simptomi, setting bundle as arguments of fragments inside SectionsPagerAdapter.
In TabbedActivity onCreate() method, get text that was passed from MainActivity
public class TabbedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
// Get text
String text = getIntent().getStringExtra("YOUR_TEXT");
// Pass text to SectionsPagerAdapter
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), text);
.............
......................
}
}
Update SectionsPagerAdapter to pass text to Fragments:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private String yourText;
public SectionsPagerAdapter(FragmentManager fm, String yourText) {
super(fm);
this.yourText = yourText;
}
#Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
bundle.putString("YOUR_TEXT", yourText);
switch (position){
case 0:
Tab1Opis tab1 = new Tab1Opis();
tab1.setArguments(bundle); // Pass text to Tab1Opis fragment
return tab1;
case 1:
Tab2Simptomi tab2 = new Tab2Simptomi();
tab2.setArguments(bundle);
return tab2;
case 2:
Tab3Uzroci tab3 = new Tab3Uzroci();
tab3.setArguments(bundle);
return tab3;
case 3:
Tab4Lijecenje tab4 = new Tab4Lijecenje();
tab4.setArguments(bundle);
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Opis";
case 1:
return "Simptomi";
case 2:
return "Uzroci";
case 3:
return "Lijecenje";
}
return null;
}
}}
3. Finally get text from individual Frgament and do whatever you want.
Update Tab2Simptomi as below:
public class Tab2Simptomi extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_simptomi, container, false);
String finalText = getArguments().getString("YOUR_TEXT");
// Do something with finalText
Toast.makeText(getActivity(), "Final Text: " + finalText, Toast.LENGTH_SHORT).show();
return rootView;
}
}
UPDATE:
Assuming your fragment texts are static.
1. Pass texts from MainActivity to TabbedActivity, using Intent extras.
Update onItemClick() as below:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
switch (i){
case 0:
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
intent.putExtra("OPIS", "Item1 :: Text for Fragment OPIS");
intent.putExtra("SIMPTOMI", "Item1 :: Text for Fragment SIMPTOMI");
intent.putExtra("UZROCI", "Item1 :: Text for Fragment UZROCI");
intent.putExtra("LIJECENJE", "Item1 :: Text for Fragment LIJECENJE");
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(MainActivity.this, TabbedActivity.class);
intent1.putExtra("OPIS", "Item2 :: Text for Fragment OPIS");
intent1.putExtra("SIMPTOMI", "Item2 :: Text for Fragment SIMPTOMI");
intent1.putExtra("UZROCI", "Item2 :: Text for Fragment UZROCI");
intent1.putExtra("LIJECENJE", "Item2 :: Text for Fragment LIJECENJE");
startActivity(intent1);
break;
}
}
});
2. Pass texts from TabbedActivity to Tab2Simptomi, setting bundle as arguments of fragments inside SectionsPagerAdapter.
In TabbedActivity onCreate() method, get text that was passed from MainActivity
public class TabbedActivity extends AppCompatActivity {
ArrayList<String> stringArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
stringArray = new ArrayList<String>();
// Get texts
String textOPIS = getIntent().getStringExtra("OPIS");
String textSIMPTOMI = getIntent().getStringExtra("SIMPTOMI");
String textUZROCI = getIntent().getStringExtra("UZROCI");
String textLIJECENJE = getIntent().getStringExtra("LIJECENJE");
// Add text to ArrayList
stringArray.add(textOPIS);
stringArray.add(textSIMPTOMI);
stringArray.add(textUZROCI);
stringArray.add(textLIJECENJE);
// Pass ArrayList to SectionsPagerAdapter
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), stringArray);
.............
......................
}
}
Update SectionsPagerAdapter to pass text to Fragments:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private ArrayList<String> stringList;
public SectionsPagerAdapter(FragmentManager fm, ArrayList<String> stringArray) {
super(fm);
this.stringList = stringArray;
}
#Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
bundle.putString("YOUR_TEXT", stringList.get(position)); // Get string from stringList using position
switch (position){
case 0:
Tab1Opis tab1 = new Tab1Opis();
tab1.setArguments(bundle); // Pass text to Tab1Opis fragment
return tab1;
case 1:
Tab2Simptomi tab2 = new Tab2Simptomi();
tab2.setArguments(bundle);
return tab2;
case 2:
Tab3Uzroci tab3 = new Tab3Uzroci();
tab3.setArguments(bundle);
return tab3;
case 3:
Tab4Lijecenje tab4 = new Tab4Lijecenje();
tab4.setArguments(bundle);
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Opis";
case 1:
return "Simptomi";
case 2:
return "Uzroci";
case 3:
return "Lijecenje";
}
return null;
}
}}
3. Finally get text from individual Frgament and do whatever you want.
Update Tab2Simptomi as below:
public class Tab2Simptomi extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_simptomi, container, false);
String finalText = getArguments().getString("YOUR_TEXT");
// Do something with finalText
TextView yourTextView = (TextView) rootView.findViewById(R.id.your_textview);
// Show text on TextView
yourTextView.setText(finalText);
Toast.makeText(getActivity(), "Final Text: " + finalText, Toast.LENGTH_SHORT).show();
return rootView;
}
}
Hope this will help~
In MainActivity
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
switch (i){
case 0:
intent.putExtra("Title", "Title1");
break;
case 1:
intent.putExtra("Title", "Title2");
break;
}
startActivity(intent);
}
});
In TabbedActivity,String title is Title1 or Title2 based on what was clicked in MainActivity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
String title = getIntent().getStringExtra("Title");
Toast.makeText(this, ""+title, Toast.LENGTH_SHORT).show();
// 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);
}
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.v(TAG, "onCreateView");
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// setting up the view pager and tab layout
mViewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
mTabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout);
PageAdapter adapter = new PageAdapter(getFragmentManager());
mViewPager.setAdapter(adapter);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
return rootView;
}
My custom pager adapter looks like this:
public class PageAdapter extends FragmentStatePagerAdapter {
public PageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new GroupTabFragment(position);
}
#Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "Game"; // this is from a template, i have to
break; // return title dynamically
case 1:
title = "Movie";
break;
}
return title;
}
#Override
public int getCount() {
return 2; // the tabs number is a subject of change
} // i don't know it from the begining
}
The problem i have is that i have to add or remove a tab when a button is clicked, or something like this.
Each tab will display a classic list of objects.
Thank you.
There are 2 ways doing this although ViewPager is not suitable for dynamic removing:
1) Pass ArrayList<Fragment> data as parameter to PageAdapter
Then Adapter will look like this:
public class PageAdapter extends FragmentStatePagerAdapter {
private ArrayList<Fragment> data;
public PageAdapter(FragmentManager fm, ArrayList<Fragment> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
return data.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "Game"; // this is from a template, i have to
break; // return title dynamically
case 1:
title = "Movie";
break;
}
return title;
}
#Override
public int getCount() {
return data.size(); // the tabs number is a subject of change
} // i don't know it from the begining
}
to remove item you do in Activity\Fragment:
data.remove(fragmentId);
adapter.notifyDataSetChanged();
2) Recreate adapter every time you want to delete item. So you basically create new adapter with new data.
data.remove(fragmentId);
PageAdapter adapter = new PageAdapter(getFragmentManager(), data);
mViewPager.setAdapter(adapter);
Instead of using mTabLayout.setupWithViewPager(mViewPager); you can setup your tabs manually:
mTabLayout.addTab(mTabLayout.newTab().setText("Movie"));
mTabLayout.addTab(mTabLayout.newTab().setText("Game"));
mTabLayout.addTab(mTabLayout.newTab().setText("Audio"));
mTabLayout.setOnTabSelectedListener(this);
Removing is also easy: removeTabAt(int position) or removeTab(Tab tab)
Here I have found some better solution to remove all the views / fragments from the current context.
Here I have used TabLayout and ViewPage within Fragment.
So we need to clear tabs from TabLayout, views from ViewPage and fragments from FragmentManager.
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
FragmentManager fragmentManager = null;
public TabLayout tabLayout;
public ViewPager viewPager;
public ViewPagerAdapter(FragmentManager manager, TabLayout tabLayout, ViewPager pager) {
super(manager);
this.fragmentManager= manager;
this.tabLayout = tabLayout;
this.viewPager= pager;
}
public void removeAll() {
tabLayout.removeAllTabs();
viewPager.removeAllViewsInLayout();
viewPager.removeAllViews();
viewPager.setAdapter(null);
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
if (manager.getFragments() != null) {
manager.getFragments().clear();
}
viewPager.setAdapter(adapterPage);
viewPager.invalidate();
viewPager.requestLayout();
mFragmentList.clear();
mFragmentTitleList.clear();
}
I've been trying to resolve this problem but with no result. My app is made up of 4 fragments, the second one with a recycler view. When I swipe from the first to the second my app instantly crashes. And in the logCat this error appears:
Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollHorizontally()' on a null object reference at android.support.v7.widget.RecyclerView.onInterceptTouchEvent(RecyclerView.java:2022)
Here's my code for the main activity:
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.app_bar);
if (toolbar != null) {
toolbar.setTitle("Quick!");
}
setSupportActionBar(toolbar);
fragmentList.add(HomeFragment.getInstance(0));
fragmentList.add(KartFragment.getInstance(1));
fragmentList.add(FavouriteFragment.getInstance(2));
fragmentList.add(ScannerFrag.getInstance(3));
pager = (ViewPager) findViewById(R.id.Pager);
pager.setAdapter(new myPagerAdapter(getSupportFragmentManager()));
tab = (SlidingTabLayout) findViewById(R.id.SlidingTab);
tab.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.accentColor);
}
});
tab.setViewPager(pager);
}
class myPagerAdapter extends FragmentPagerAdapter {
String[] tabs;
public myPagerAdapter(FragmentManager fm) {
super(fm);
tabs = getResources().getStringArray(R.array.tabs);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
public int getCount() {
return fragmentList.size();
}
}
Home fragment:
public class HomeFragment extends Fragment {
private Toolbar toolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout;
layout = inflater.inflate(R.layout.home_layout, container, false);
toolbar = (Toolbar) layout.findViewById(R.id.subToolbar);
toolbar.setTitle("Dove mangi oggi?");
return layout;
}
public static HomeFragment getInstance(int position) {
HomeFragment frag = new HomeFragment();
Bundle args = new Bundle();
args.putInt("position", position);
frag.setArguments(args);
return frag;
}
}
KartFragment:
public class KartFragment extends Fragment {
private Toolbar toolbar;
private ItemAdapter ad;
private RecyclerView rv;
private ArrayList list = new ArrayList<>();
private static final String SAVELIST = "SAVELIST";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View layout;
if (savedInstanceState != null) {
list = savedInstanceState.getParcelableArrayList(SAVELIST);
} else {
list = KartObjectClass.listBuilder(10);
}
layout = inflater.inflate(R.layout.fragment_layout, container, false);
toolbar = (Toolbar) layout.findViewById(R.id.subToolbar);
toolbar.setTitle("I tuoi ordini:");
rv = (RecyclerView) layout.findViewById(R.id.list);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
ad = new ItemAdapter(list);
rv.setHasFixedSize(true);
rv.setAdapter(ad);
return layout;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList(SAVELIST, list);
super.onSaveInstanceState(outState);
}
public static KartFragment getInstance(int position) {
KartFragment frag = new KartFragment();
Bundle args = new Bundle();
args.putInt("position", position);
frag.setArguments(args);
return frag;
}
}
Favourite fragment:
public class FavouriteFragment extends Fragment {
private Toolbar toolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = null;
layout = inflater.inflate(R.layout.scanner_layout, container, false);
toolbar = (Toolbar) layout.findViewById(R.id.subToolbar);
toolbar.setTitle("I tuoi preferiti:");
return layout;
}
public static FavouriteFragment getInstance(int position) {
FavouriteFragment frag = new FavouriteFragment();
Bundle args = new Bundle();
args.putInt("position", position);
frag.setArguments(args);
return frag;
}
}
Try to set the LayoutManager before you set the Adapter on the RecyclerView.
I solved the error, the problem was that I had set a recycler view in the homeFragment XML. As I forgot to have it, I didn't call it in the onCreateView method and the app was crashing because no adapter was set.
This is my page:
package[...]
import [...]
public class Home extends FragmentActivity {
ViewPager mViewPager;
ListView list;
row_video_Adapter adapter;
public Home CustomListView = null;
public ArrayList<ModelloLista> CustomListViewValuesArr = new ArrayList<ModelloLista>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// ListView
CustomListView = this;
/******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/
setListData();
Resources res =getResources();
list= (ListView)findViewById(R.id.section_label); // List defined in XML ( See Below )
/**************** Create Custom Adapter *********/
adapter=new row_video_Adapter(CustomListView, CustomListViewValuesArr,res);
list.setAdapter(adapter);
}
/****** Function to set data in ArrayList *************/
public void setListData(){
final ModelloLista sched = new ModelloLista();
sched.setTitolo("Video 1");
sched.setImmagine("video_preview");
sched.setUrl("http:\\www.com");
CustomListViewValuesArr.add(sched);
}
/***************** This function used by adapter ****************/
public void onItemClick(int mPosition){
ModelloLista tempValues = ( ModelloLista ) CustomListViewValuesArr.get(mPosition);
// SHOW ALERT
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
#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 null;
}
}
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_dummy,
container, false);
//TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
switch(getArguments().getInt(ARG_SECTION_NUMBER)){
case 1:
//dummyTextView.setText("text 1");
break;
case 2:
[...]
}
return rootView;
}
}
}
How can I put my Custom ListView in a fragment?
I tried to move the code in the switch(getArguments().getInt(ARG_SECTION_NUMBER)){ but there were many errors.
What should I do?