Incompatilble types in my FragmentPagerAdapter - android

I get an error when I try to return a new fragment. I suspect it has something to do with the imports but I must be wrong using just Android's fragmentpageradapter does not change anything, I'm out of ideas and just want it to work so I can see it in the emulator running.
My FragmentPagerAdapter class:
import android.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by HP_user on 01/12/2015.
*/
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[] { "Home", "Shouts", "Shouters" };
public SampleFragmentPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public int getCount() { return PAGE_COUNT; }
#Override
public android.Fragment getItem(int position) {
return Home.newInstance(position + 1);
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
My main activity class:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
// Give the PagerSlidingTabStrip the ViewPager
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
// Attach the view pager to the tab strip
tabsStrip.setViewPager(viewPager);
}
}
Main activity fragment class:
public class MainActivityFragment extends Fragment {
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_page, container, false);
}
}

The problem is that the android.support.v4.app.FragmentPagerAdapter class can only be used with support Fragments, i.e. android.support.v4.app.Fragment.
You have two choices to fix it.
Choice 1) Make all of your Fragments android.support.v4.app.Fragment instances instead of android.app.Fragment instances.
Choice 2) Use the android.support.v13.app.FragmentPagerAdapter class from the v13 support library, which makes it possible to use regular Fragments, see documentation here.

Related

Tab Slider Android Studio not working

I set up a tab slider in my activity calling 3 separate fragments depending on the fragment selected. The problem is that when the first tab is selected, "Science" is shown - which was set on the onCreateView() method of the first fragment. However, WITHOUT clicking on the other tabs, "Technology" and "Sports" are then shown.
To my knowledge, the way I implemented it the last two should only show once the corresponding tab is selected.
This is my Page adapter class
public class PagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3; //Represents the number of tabs
private String tabTitles[] = new String[]{"Technology", "Science", "Sports"}; //Tab values defined in an array
private Context context;
public PagerAdapter(FragmentManager fm, Context context)
{
super(fm);
this.context = context;
}
#Override
public int getCount()
{
return PAGE_COUNT;
}
//determines the fragment depending on the selected tab
#Override
public Fragment getItem(int position)
{
if(position==0)
return TechnologyFragment.newInstance(position+1);
else if(position==1)
return ScienceFragment.newInstance(position+1);
else if(position==2)
return SportsFragment.newInstance(position+1);
else
return null;
}
//displays the title for each tab
#Override
public CharSequence getPageTitle(int position)
{
// Generate title based on item position
return tabTitles[position];
}
}
This is the news class - where the view pager and tab layout are set up
public class News extends AppCompatActivity {
//Here the viewPager is connected to the PagerAdapter class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
//This component will be used to page between the various fragments created.
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager(), News.this));
//the tabLayout is given the viewPager to connect to the pager with the tabs
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
//the following was used so the tabs fill up the width of the screen being responsive for all devices and orientations
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
}
}
And these are the fragment classes - (the other two are identical but have a different message represented using the Toast)
public class ScienceFragment extends Fragment {
//other methods
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_science_fragment, container, false);
toShow=getAll();
GridView gridView = (GridView)view.findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(getContext(),toShow));
Toast.makeText(getContext(), "Science", Toast.LENGTH_SHORT).show();
return view;
}
}
Any help is appreciated

Unable to add "android.app.Fragment" to FragmentPagerAdapter [duplicate]

I get an error when I try to return a new fragment. I suspect it has something to do with the imports but I must be wrong using just Android's fragmentpageradapter does not change anything, I'm out of ideas and just want it to work so I can see it in the emulator running.
My FragmentPagerAdapter class:
import android.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by HP_user on 01/12/2015.
*/
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[] { "Home", "Shouts", "Shouters" };
public SampleFragmentPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public int getCount() { return PAGE_COUNT; }
#Override
public android.Fragment getItem(int position) {
return Home.newInstance(position + 1);
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
My main activity class:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
// Give the PagerSlidingTabStrip the ViewPager
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
// Attach the view pager to the tab strip
tabsStrip.setViewPager(viewPager);
}
}
Main activity fragment class:
public class MainActivityFragment extends Fragment {
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_page, container, false);
}
}
The problem is that the android.support.v4.app.FragmentPagerAdapter class can only be used with support Fragments, i.e. android.support.v4.app.Fragment.
You have two choices to fix it.
Choice 1) Make all of your Fragments android.support.v4.app.Fragment instances instead of android.app.Fragment instances.
Choice 2) Use the android.support.v13.app.FragmentPagerAdapter class from the v13 support library, which makes it possible to use regular Fragments, see documentation here.

How can I access localised strings from within a static FragmentPagerAdapter

I have followed official documentation on how to implement swipe views with TabStrip instead of Tabs in order to create a Fragment (FragmentMyAccount.class) that contains Nested Fragments (FragmentMyProfile.class and FragmentMyLibrary.class). These nested fragments correspond to the two tabs managed by a childFragmentManager.
The two tabs and astuetz's pagerSlidingTabStrip work fine, but adapter's getPageTitle method doesn't have access to String resources and can only return a hardcoded string for each tab title (see on the bottom of the code). The compile-time error that appears when I try to access the xml resources reads:
"FragmentMyAccount.this cannot be referenced from a static context"
If the code below is not possible to tweak, what alternative implementation would be adequate to achieve my goal?
package com.kouretinho.myapp;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.astuetz.PagerSlidingTabStrip;
public class FragmentMyAccount extends Fragment {
private static final int NUM_ITEMS = 2;
MyAccountAdapter mAdapter;
ViewPager mPager;
PagerSlidingTabStrip mTabStrip;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my_account, container, false);
// Initialize the FragmentPager Adapter
mAdapter = new MyAccountAdapter(getChildFragmentManager());
// Initialize the ViewPager and set an adapter
mPager = (ViewPager) rootView.findViewById(R.id.viewpager_my_account);
mPager.setAdapter(mAdapter);
// Initialize the TabStrip and bind the tabs to the ViewPager
mTabStrip = (PagerSlidingTabStrip) rootView.findViewById(R.id.viewpager_tab_strip);
mTabStrip.setViewPager(mPager);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
public static class MyAccountAdapter extends FragmentPagerAdapter{
private static final int MY_PROFILE = 0;
private static final int MY_LIBRARY = 1;
private static final String sExceptionMessage = "FragmentPagerAdapter was asked to getItem " +
"with position other than 0 or 1. This FragmentPagerAdapter can only return one of" +
"two Fragments at position 0 or 1.";
public MyAccountAdapter(FragmentManager fm){
super(fm);
}
#Override
public int getCount() {
return FragmentMyAccount.NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position){
case MY_PROFILE:
return new UserProfileFragment();
case MY_LIBRARY:
return new UserBooksFragment();
default:
throw new IllegalStateException(sExceptionMessage);
}
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case MY_PROFILE:
// ********** THIS LINE IS PROBLEMATIC, cannot get Localised String resources
return FragmentMyAccount.this.getActivity().getResources().getString(R.id.my_profile);
case MY_LIBRARY:
return "my_library";
default:
return "no_title";
}
}
}
}
In your case you have to replace:
public static class MyAccountAdapter extends FragmentPagerAdapter
with
public class MyAccountAdapter extends FragmentPagerAdapter
Another way to fix this is to pass Context to MyAccountAdapter in constructor (like you do with FragmentManager).

Change Fragment with ViewPager

I am using PagerSlidingTab Library for ViewPager. And I want to change Fragment while scrolling of tabs. It is working fine. Check out my code.
I am using AsynTask() on each Fragment.
When the App opens with the MainActivity, First Fragment is attached to the activity, But It shows two AsynTask() dialog message, one from First and another from Second Fragment. And When I scroll to second tab, It shows dialog message of Third Fragment.
So, If I scroll from left to right in tabs, the Fragment right to the current fragment is displayed and if i scroll from right to left, the Fragment left to the current Fragment is displayed.
Please help me to solve the problem.
My Code:
public class PageSlidingTabStripFragment extends Fragment {
public static final String TAG = PageSlidingTabStripFragment.class
.getSimpleName();
public static PageSlidingTabStripFragment newInstance() {
return new PageSlidingTabStripFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.pager, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) view
.findViewById(R.id.tabs);
ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
private final String[] TITLES = { "Instant Opportunity", "Events",
"Experts" };
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new InstantOpportunity();
case 1:
return new Events();
case 2:
return new Experts();
default:
break;
}
return null;
}
}
}
Explanation:
It turns out there is an easier implementation for scrollable tabs which doesn't involve another library. You can easily implement tabs into your app using normal Android code straight from the default SDK.
The Code
Main Class:
public class PageSlidingTabStripFragment extends Fragment {
//Variables
private ViewPager viewPager;
private PagerTitleStrip pagerTitleStrip;
public PageSlidingTabStripFragment() {
// Required empty public constructor
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Find your pager declared in XML
viewPager = (ViewPager) getView().findViewById(R.id.pager);
//Set the viewPager to a new adapter (see below)
viewPager.setAdapter(new MyAdapter(getFragmentManager()));
//If your doing scrollable tabs as opposed to fix tabs,
//you need to find a pagerTitleStrip that is declared in XML
//just like the pager
pagerTitleStrip = (PagerTitleStrip)
getView().findViewById(R.id.pager_title_strip);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.[your layout name here], container, false);
}
}
Adapter:
//Note: this can go below all of the previous code. Just make sure it's
//below the last curly bracket in your file!
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment = null;
if (arg0 == 0) {
fragment = new InstantOpportunity();
}
if (arg0 == 1) {
fragment = new Events();
}
if (arg0 == 2) {
fragment = new Experts();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Instant Opportunity";
}
if (position == 1) {
return "Events";
}
if (position == 2) {
return "Experts";
}
return null;
}
}
Conclusion:
I hope this helps you understand another way to make scrollable tabs! I have examples on my Github Page about how to make each type (That being Fixed or Scrollable).
Links:
Fixed Tabs Example - Click Here
Scrollable Tabs Example - Click Here
Hope this helps!
Edit:
When asked what to import, make sure you select the V4 support fragments.
please use this example..its very easy.i already implement that.
reference link
hope its useful to you.its best example of pager-sliding-tabstrip.
Use
framelayout compulsory:
FrameLayout fl = new FrameLayout(getActivity());
fl.addView(urFragementView);
and then set your fragement view in this framelayout.

Access TextView in ViewPager from Activity

I have an Activity with a ViewPager containing multiple fragments. how can i now access a TextView in one of that fragments to change its text from the main activity? I tried multiple ways and they all ended in a NullPointerException.
Activity:
public class SummonerOverview extends SherlockFragmentActivity implements TabListener, OnPageChangeListener {
private ViewPager mPager;
private PagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.summoner_overview);
initialize();
}
private void initialize() {
// initialize Pager
mPager = (ViewPager) findViewById(R.id.viewpager);
mAdapter = new PagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(1);
mPager.setOnPageChangeListener(this);
}
}
PagerAdapter:
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
frags = new Fragment[3];
frags[0] = new StatisticsFragment(0);
frags[1] = new RatingsFragment(1);
frags[2] = new HistoryFragment(2);
}
private final int NUM_PAGES = 3;
Fragment[] frags;
#Override
public Fragment getItem(int arg0) {
if (arg0 == 0)
return frags[0];
else if (arg0 == 1)
return frags[1];
else
return frags[2];
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
The Fragment:
public class StatisticsFragment extends SherlockFragment {
public StatisticsFragment(int fragNr) {
this.fragNr = fragNr;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_overview_statistics, container, false);
return v;
}
}
The Textview in the StatisticsFragment is labeled with an id in the fragment_overview_statistics.xml, but when i try
TextView tv = (TextView) findViewById(R.id.id_of_the_textview)
tv.setText("text");
from within the onCreate() Method of the Activity after the initialize() Method, i get an Exception.
Okay, after another hour of googling, i think i solves my own question (although i'm sure there is a better method to solve that)
I now hold all the Data that is displayed by the fragments in the MainActivity and make the Fragmets consume this Data in their onCreateView() Method by using public Methods of the Activity.
In the PagerAdapter, i overwrote getItemPosition() to:
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Now, everytime i update some of the Data, i also call mAdapter.notifyDataSetChanged() which leads into a recreation of all fragments.
It works, although it looks like a poor hack for me. Im sure there must be a better solution because now i have to recreate all fragments for changing one TextView of one Fragment, what is surely not the way it is intended to be done.

Categories

Resources