Android swiping, using ViewPager without tabs - android

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);
}

Related

Getting application context into fragment, ViewPager

I'm writing a simple app with swipe view using viewpager and fullscreen fragments. In one of fragments I want to check internet connection status before displaying some data but I can't get the application context. I've found a lot of topics on this issue, but none of solutions works for me. I am using getApplication() within fragment but even though I get error "Unreacheable statement".
Any advice?
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting fragment view pager
viewPager = (ViewPager)findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
activity_main.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
First fragment
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CurrentWeatherFragment extends Fragment {
//flaga dla statusu polaczenia z internetem
Boolean isInternetPresent = false;
//klasa detektora połączenia
ConnectionDetector cd;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.currentweather, container, false);
return v;
//tworzenie klasy detektora
cd = new ConnectionDetector(getActivity().getApplicationContext());
//sprawdzenie czy jest polaczenie z internetem
isInternetPresent = cd.isConnectingToInternet();
}
}
Pager Adapter class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
switch (arg0){
case 0:
return new CurrentWeatherFragment();
case 1:
return new ForecastFragment();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
In the CurrentWeatherFragment's onCreateView you inflate the View then instantly return it.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.currentweather, container, false);
return v;
//tworzenie klasy detektora
cd = new ConnectionDetector(getActivity().getApplicationContext());
//sprawdzenie czy jest polaczenie z internetem
isInternetPresent = cd.isConnectingToInternet();
}
Move the return v; to the end of the method:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.currentweather, container, false);
//tworzenie klasy detektora
cd = new ConnectionDetector(getActivity().getApplicationContext());
//sprawdzenie czy jest polaczenie z internetem
isInternetPresent = cd.isConnectingToInternet();
return v;
}
Could be a lifecycle problem. Make that call in onAttach(Activity) instead of in onCreateView()

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).

Moving From one tab view to another by button Click Android ActionBar

I am using http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/ to make Tab bar.I have also 3 tab first and the second Tab view contains a List view and third on e is Settings. Settings Contain Reload button. When I clicked the Reload Button I want to move to First Tab.How can I do this ?
Make following changes:
Pass the viewPager reference to your adapter and from adapter to your fragment:
public class TabsPagerAdapter extends FragmentPagerAdapter {
ViewPager viewPager;
public TabsPagerAdapter(FragmentManager fm,ViewPager viewPager) {
super(fm);
this.viewPager=viewPager;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment(viewPager);
case 1:
// Games fragment activity
return new GamesFragment(viewPager);
case 2:
// Movies fragment activity
return new MoviesFragment(viewPager);
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
In fragment on click of button call set selection on view pager object:
public class MoviesFragment extends Fragment {
private ViewPager viewPager;
public MoviesFragment (ViewPager viewPager;){
this.viewPager=viewPager;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
rootView.findViewById(<your button>).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
viewPager.setCurrentItem(0);
}
});
return rootView;
}
}
I know its quite late ....maybe it can help someone else...creating a constructor in fragments is not supported..so instead of passing viewpager as constructor..
we can write in the fragment on button click:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by medha singh on 6/17/2016.
*/
public class Fragment4 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View view1 = inflater.inflate(R.layout.new_lead2, container, false);
TextView tv=(TextView)view1.findViewById(R.id.hardware);
final ViewPager pager= (ViewPager)getActivity().findViewById(R.id.pager2);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pager.setCurrentItem(1);
}
});
return view1;
}
}
So getactivity() is the solution: i got it from here: How to go other Tabs by clicking on a Button from the current Tab in Android?
Do this:
btn.setOnClickListener(new OnClickListener()
{
onClick(View v)
{
//Reload the data
tabHost.setCurrentTab(/*destination-tab-id*/);
}
}
)

android error implementing pager on fragment

Im implementing a pager inside a fragment, but i get this error
The method getSupportFragmentManager() is undefined for the type
HowToUse_phone
on
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
here the code,
package com.chocte.ks_documents;
import java.util.Locale;
import android.os.Bundle;
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 android.widget.LinearLayout;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
public class HowToUse_phone extends SherlockFragment{
private LinearLayout lLayoutFrgHow;
ViewPager mViewPager;
SectionsPagerAdapter mSectionsPagerAdapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
//return inflater.inflate(R.layout.activity_how_phone, container, false);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
//mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager = (ViewPager) getView().findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//get the layou8t
lLayoutFrgHow=(LinearLayout) inflater.inflate(R.layout.activity_how_phone, container, false);
return lLayoutFrgHow;
}
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 DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
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 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
//return getString(R.string.title_section1).toUpperCase(l);
return "a";
case 1:
//return getString(R.string.title_section2).toUpperCase(l);
return "b";
case 2:
//return getString(R.string.title_section3).toUpperCase(l);
return "c";
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* 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_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
}
I saw is some problems when importing fragment, but as you see in my code im android.support.v4.app...
what else is the problem?
thanks!
Instead of calling getSupportFragmentManager() call getSherlockActivity().getSupportFragmentManager(). You're now trying to call a method from SherlockActivity but you're in SherlockFragment; that's why you need to get a ref first to SherlockFragment object ...
But above will fix only the compile error ... I am not sure if you have any other problems in your code. According to previous answer you didn't instantiate your fragment view at the proper time.
You are trying to fetch the View, before you have inflated the Layout.
Assuming R.layout.activity_how_phone contains the Id to the ViewPager your trying to fetch here:
mViewPager = (ViewPager) getView().findViewById(R.id.pager);
It should be something like this:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
lLayoutFrgHow=(LinearLayout) inflater.inflate(R.layout.activity_how_phone, container, false);
mViewPager = (ViewPager) lLayoutFrgHow.findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//get the layout
return lLayoutFrgHow;
Besides that, why are you using a ViewPager within a Fragment? Usually its used wtihin an Activity, and it is hosting the Fragments.
And in addition your using 2 Different Kinds of Fragments. In your ViewPager you are using Fragments from support v4, and your Class is a SherlockFragment.

Android - Getting context of a fragment in a pager

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()));

Categories

Resources