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).
Related
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.
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.
Im using FragmentPagerAdapter and ViewPager to show two fragments. First time when open the fragment, both show/work fine. When I go to another activity or go to another fragment outside these 2 and come back, nothing shows up. Here's the code.
Event:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Events extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.event, container, false);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.pager);
FragmentManager fm = getFragmentManager();
viewPager.setAdapter(new MyFragmentPageAdapter(fm));
// Give the SlidingTabLayout the ViewPager
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
// Center the tabs in the layout
slidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.ColorSecondary);
}
});
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setViewPager(viewPager);
return rootView;
}
}
MYFramentAdapter.class:
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPageAdapter extends FragmentPagerAdapter{
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "Upcoming", "Calendar" };
private Context context;
public MyFragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FragmentEvents.newInstance(0);
case 1: return FragmentCalendar.newInstance(1);
default: return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
Resolved:
I had to user getChildFragmentManager() in ViewPager because of nested fragments.
I have a android application using a pager as navigation. For the tabs I have 3 layouts as content. On one of the fragments is a gallery and I want to add images to it. For that I have to set an ImageAdapter but I need to know how to access the context of a fragment.
final LayoutInflater factory = getLayoutInflater();
final View view = factory.inflate(R.layout.pictures, null);
Gallery g = (Gallery) view.findViewById(R.id.gallery1);
g.setAdapter(new ImageAdapter(view.getContext()));
I use this code above in the onCreate method to get the gallery from a layout that is not the contentview.
I have to give a Context to the ImageAdapter. But what context do I have to set there?
EDIT: This is my complete code:
package com.bw2801.uwelugemediathek;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Context;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
PicturesSectionFragment ps = new PicturesSectionFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// 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);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
final LayoutInflater factory = getLayoutInflater();
final View view = factory.inflate(R.layout.pictures, null);
Gallery g = (Gallery) view.findViewById(R.id.gallery1);
g.setAdapter(new ImageAdapter(ps.getActivity()));
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Integer[] mImageIds = {
R.drawable.image01,
R.drawable.image02,
R.drawable.image03,
R.drawable.image04,
R.drawable.image05,
R.drawable.image06,
R.drawable.image07,
R.drawable.image08,
};
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
return i;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return new DummySectionFragment();
case 1:
return new SoundSectionFragment();
case 2:
return ps;
}
return new DummySectionFragment();
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Informationen";
case 1:
return "Soundboard";
case 2:
return "Galerie";
}
return null;
}
}
public static class DummySectionFragment extends Fragment {
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.info, container, false);
}
}
public static class PicturesSectionFragment extends Fragment {
public PicturesSectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.pictures, container, false);
}
}
public static class SoundSectionFragment extends Fragment {
public SoundSectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.sounds, container, false);
}
}
}
Fragments don't have their own Context, they use parent Activity.
To get parent Activity Context, use getActivity()
To use Application Context, use getActivity().getApplicationContext()
Prefer Application Context wherever possible.
UPDATE:
getActivity() of a Fragment returns an Activity instance if and only if, the said Fragment is currently attached to an Activity.
So,
Fragment f = new MyFragment();
creates a fragment, but it is not attached to an activity yet. Hence f.getActivity() returns null.
After its added to an activity:
getFragmentManager().beginTransaction().add(f,"fragment").commit();
Now, getActivity() will return an Activity instance.
Again, if we detach the fragment from Activity:
getFragmentManager().beginTransaction().detach(f).commit()
getActivity() will again return a null value.
So, we should not use getActivity() outside the Fragment class, because we can't be sure of attached status. Thus I'll advice you to used getActivity() inside the fragment's own class in its methods: onAttach(), onCreate() or onActivityCreated().
you can use like this
g.setAdapter(new ImageAdapter(getActivity()));
The easiest and most precise way to get the context of the fragment that I found is to get it directly from the ViewGroup when you call onCreateView method at least here you are sure not to get null for getActivity()
public class Animal extends Fragment {
Context thiscontext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
thiscontext = container.getContext();
write under code in Your CoreApplication.java
step1)
public class CoreApplication extends Application {
private static CoreApplication instance;
}
step2) onCreate(){
instance = this;
}
step3 )
add under method()
public static CoreApplication getGlobalApplicationContext() {
if (instance == null) {
throw new IllegalStateException("this application does not
inherit GlobalApplication"); " +
"}
return instance;
}
Step4)
g.setAdapter(new ImageAdapter(getGlobalApplicationContext()));
Im trying to make an app that have the navigation type of swiping.
This is how far I have gone:
Fragment activity:
package com.app.BoomBase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment_control extends Fragment {
String tag = this.getClass().getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(tag, "onCreate");
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
Bundle data = getArguments();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i(tag, "onCreateView");
View view = inflater.inflate(R.layout.fragment_controle,container, false );
return view;
}
}
FragmentPageAdapter:
package com.app.BoomBase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class Fragment_Pager extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
public Fragment_Pager(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
Fragment_control myFragment = new Fragment_control();
Bundle data = new Bundle();
data.putInt("current_page", arg0+1);
myFragment.setArguments(data);
return myFragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return PAGE_COUNT;
}
}
MainActivity:
package com.app.BoomBase;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
String tag = this.getClass().getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(tag, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Getting a reference to the ViewPager defined the layout file */
ViewPager pager = (ViewPager) findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = getSupportFragmentManager();
/** Instantiating FragmentPagerAdapter */
Fragment_Pager pagerAdapter = new Fragment_Pager(fm);
/** Setting the pagerAdapter to the pager object */
pager.setAdapter(pagerAdapter);
}
}
But my problem is that i can't figure out how to add fragments to the code. I want to swipe to the next activity with buttons and stuff on them. How do I do that ?
PageAdapter uses your getItem() to switch between Fragments, this is where you would declare which page does what. "Position" 0 is the first page, 1 is the second and so forth. You can simply return a new instance of your other Fragments or pass arguments if you wish.
For example:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// Your current main fragment showing how to send arguments to fragment
Fragment_control myFragment = new Fragment_control();
Bundle data = new Bundle();
data.putInt("current_page", position+1);
myFragment.setArguments(data);
return myFragment;
case 1:
// Calling a Fragment without sending arguments
return new MySecondFragment();
case 2:
return new MyThirdFragment();
default:
return null;
}
}
Then you would create a Fragment class for each of those you want to incorporate. In my example you would have a class for MySecondFragment and MyThirdFragment
public class MySecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.second_fragment, null);
return view;
}
}
And
public class MyThirdFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.third_fragment, null);
return view;
}
}
Any fragment may simply inflate a standard xml layout file, to access the children in the layout you would have to remember to use the following, I'll use MySecondFragment as an example.
Let's say you have two Buttons with id's R.id.button1 and R.id.button2 in a layout file titled 'second_fragment':
public class MySecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.second_fragment, null);
// Make sure to add the parent inflater before and layout child call
Button btn_one = (Button)view.findViewById(R.id.button1);
Button btn_two = (Button)view.findViewById(R.id.button2);
return view;
}
}
Edit
To start at a page other then 0 or the first position you would simply use setCurrentItem() in your MainAvticity, like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(tag, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
FragmentManager fm = getSupportFragmentManager();
Fragment_Pager pagerAdapter = new Fragment_Pager(fm);
// Here you would declare which page to visit on creation
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(1);
}
I have added this in fragment class ..
the issue i got is cannot resolve cannot resolve get support fragment manager ().
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(tag, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
FragmentManager fm = getSupportFragmentManager();
Fragment_Pager pagerAdapter = new Fragment_Pager(fm);
// Here you would declare which page to visit on creation
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(1);
}