Im having a problem here. i downloaded jake wharton. He gave an example of that which works great. But i want is from this i want to change that recent recent recent text to an activity.. so what i did is this , i put a class with .getname in there.. i thought it will be an activity but it convert it to text? this is the code of jake..
Test Fragment.java
package com.simple.viewpage;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public final class TestFragment extends Fragment {
private static final String KEY_CONTENT = "TestFragment:Content";
public static TestFragment newInstance(String content) {
TestFragment fragment = new TestFragment();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 20; i++) {
builder.append(content).append(" ");
}
builder.deleteCharAt(builder.length() - 1);
fragment.mContent = builder.toString();
return fragment;
}
private String mContent = "???";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mContent = savedInstanceState.getString(KEY_CONTENT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView text = new TextView(getActivity());
text.setGravity(Gravity.CENTER);
text.setText(mContent);
text.setTextSize(20 * getResources().getDisplayMetrics().density);
text.setPadding(20, 20, 20, 20);
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout.setGravity(Gravity.CENTER);
layout.addView(text);
return layout;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_CONTENT, mContent);
}
}
Test FragmentAdapter.java
package com.simple.viewpage;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
class TestFragmentAdapter extends FragmentPagerAdapter {
protected static final String[] CONTENT = new String[] { "This", "Is", "A", "Test", };
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
and this is his main activity:
package com.viewpagerindicator.sample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import com.viewpagerindicator.TabPageIndicator;
public class SampleTabsDefault extends BaseSampleActivity {
private static final String[] CONTENT = new String[] { "Recent", "Artists", "Albums", "Songs", "Playlists", "Genres" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_tabs);
mAdapter = new GoogleMusicAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
class GoogleMusicAdapter extends TestFragmentAdapter {
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(SampleTabsDefault.CONTENT[position % SampleTabsDefault.CONTENT.length]);
}
#Override
public int getCount() {
return SampleTabsDefault.CONTENT.length;
}
#Override
public CharSequence getPageTitle(int position) {
return SampleTabsDefault.CONTENT[position % SampleTabsDefault.CONTENT.length].toUpperCase();
}
}
}
I change the Content String to this:
private static final String[] CONTENT = new String[] { "Recent", "Artists", "Albums", "Songs", "Playlists", "Genres",ListTest.class.getName() };
Please help.. I want to view an activity and not convert it to text..
Please help.. I want to view an activity and not convert it to text..
You don't view an Activity, you view a Fragment. And you're not converting it, just retrieving its class name and using that as the label in the pager indicator.
I change the Content String to this:
Those are just the labels. The contents are different. The content is retrieved in:
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(SampleTabsDefault.CONTENT[position % SampleTabsDefault.CONTENT.length]);
}
Jake put that code just an example.
It's up to you to switch(position) and return a new Fragment depending on the position you want to appear. I don't use that method (mine is slightly different), but how exactly you want to implement is up to you.
If you have other questions just ask. :-)
edited: a possible example:
static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
Fragment f;
switch(position) {
case 0:
f= new PlaceDataFragment();
break;
case 1:
f= new PlaceSelectorFragment();
break;
default:
throw new IllegalArgumentException("not this many fragments: " + position);
}
//DebugUtils.debugUI("getView(): " + f.toString());
return f;
}
}
Related
I'm trying to create VeiwPager inside a Fragment using FragmentStatePagerAdapter.
it displays the first fragment but after scrolling to the second fragment there is just white fragment (even on scrolling back to the first fragment)
I've tried to use PagerAdapter and set pictures without fragment but the result is same.
is there RAM problem ? what can I do to solve it?
Home fragment(contains ViewPager) :
private void initSlideShow(View view){
VPImageSlider = (ViewPager16by9) view.findViewById(R.id.VPImageSlider);
sliderDotsPanel = (LinearLayout) view.findViewById(R.id.SliderDots);
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_1);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_2);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_3);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_4);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_5);
VPImageSlider.setAdapter(vpImageSliderAdapter);
}
ViewPager Fragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import iranelab.samsoft.net.iranelab.Classes.ImageView16by9;
import iranelab.samsoft.net.iranelab.R;
public class ViewPagerFragment extends Fragment {
private static final String ARG_PARAM4 = "imageTest";
private int imageTest;
public ViewPagerFragment() {}
public static ViewPagerFragment newInstance(String imageId, String type, String text,int imageTest) {
ViewPagerFragment fragment = new ViewPagerFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM4, imageTest);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
imageTest = getArguments().getInt(ARG_PARAM4);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
ImageView16by9 image = (ImageView16by9) view.findViewById(R.id.IVSlide);
image.setImageResource(imageTest);
return view;
}
}
ViewPager Adapter :
public class VPImageSliderAdapter extends FragmentStatePagerAdapter {
private int[] slides = {};
public VPImageSliderAdapter(FragmentManager fm){
super(fm);
}
public void addSlide(int drawable){
slides = Arrays.copyOf(slides,slides.length+1);
slides[slides.length-1]=drawable;
}
#Override
public int getCount() {
return slides.length;
}
#Override
public Fragment getItem(int position) {
return ViewPagerFragment.newInstance(slides[position]);
}
}
Change
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());
to
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getChildFragmentManager());
it will work
Just needed to add :
ViewPager.setOffscreenPageLimit(5);
i'm back here with a new Question. So at the moment i created an app , that can switch from a fragment to another fragment when you click on a button. And inside those 2 fragments there is 2 viewPagers, whose create a custom number of buttons. But the problem is that when i switch from a fragment to the other one, and then i switch back , the content of the first one is no longer here. I tried a lot of things and nothing really help me. And i hope you can help me. Thanks in advance.
The Main Activity :
public class MainActivity extends AppCompatActivity {
String identifiant=null;
BottomBar bottombar;
ProgressBar progressBar;
ImageButton imageButton;
TextView nomson;
RelativeLayout aaaa;
FragmentWhizz fragmentWhizz;
FragmentPlaylist fragmentPlaylist;
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autorisation();
fragmentWhizz = new FragmentWhizz();
fragmentPlaylist=new FragmentPlaylist();
Fragment fragment = new FragmentConnexion();
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.contentFragment, fragment);
transaction.commit();
bottombar = (BottomBar) findViewById(bottomBar);
aaaa = (RelativeLayout) findViewById(R.id.aaaa);
bottombar.setVisibility(View.INVISIBLE);
bottombar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
if (tabId == R.id.tab_whiz) {
if(identifiant !=null){
changementFragment(fragmentWhizz);
}
}
if (tabId == R.id.tab_playlist) {
if(identifiant !=null){
changementFragment(fragmentPlaylist);
}
}
if (tabId == R.id.tab_reveil) {
if(identifiant !=null){
changementFragment(new FragmentReveil());
}
}
if (tabId == R.id.tab_param) {
if(identifiant !=null){
changementFragment(new FragmentParam());
}
}
}
});
}
public void changementFragment(final Fragment fragment){
runOnUiThread(new Runnable() {
public void run() {
fm = getFragmentManager();
FragmentTransaction ft =fm.beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in,android.R.animator.fade_out);
ft.replace(R.id.contentFragment, fragment).commit();
}
});
}
}
One of the 2 fragments that have the ViewPager:
public class FragmentPlaylist extends Fragment {
SlideToutesPlaylist fragmentAllPlaylist = new SlideToutesPlaylist();
SlideUserPlaylist fragmentUserPlaylist = new SlideUserPlaylist();
ViewPager mViewPager;
FloatingActionButton floatbutton;
private FragmentActivity myContext;
#Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.playlist, container, false);
DeplacerBoutton deplacer = new DeplacerBoutton(getActivity(),2);
floatbutton = (FloatingActionButton) myView.findViewById(R.id.floatingActionButton);
floatbutton.setOnTouchListener(deplacer);
mViewPager = (ViewPager) myView.findViewById(R.id.slide);
mViewPager.setAdapter(new SamplePagerAdapter(myContext.getSupportFragmentManager()));
Log.i("test","test");
return myView;
}
public class SamplePagerAdapter extends FragmentStatePagerAdapter {
SamplePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
/** Show a Fragment based on the position of the current screen */
if (position == 0) {
return fragmentAllPlaylist;
} else
return fragmentUserPlaylist;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
}
And finally one fragment displayed on the viewPager:
public class SlideToutesPlaylist extends Fragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.playlistall, container, false);
AffichePlaylist(myView);
return myView;
}
public void AffichePlaylist(View myView){
ExecHttpGetRequest requete = new ExecHttpGetRequest();
requete.execute("an IP");
LinearLayout aaa = (LinearLayout) myView.findViewById(R.id.aaa);
try {
if (requete.get() != null) {
JSONObject jsonObj = new JSONObject(requete.get());
JSONArray jSon = jsonObj.getJSONArray("valeurs");
for (int i = 0; i < jSon.length(); i++) {
JSONObject c = jSon.getJSONObject(i);
final String nom_playlist = c.getString("nom_playlist");
final String id_playlist = c.getString("id_playlist");
final String id_createur = c.getString("id_createur");
final String nb_vote = c.getString("nb_vote");
Button bouton = new Button(getContext());
bouton.setText(nom_playlist);
aaa.addView(bouton);
}
}
} catch (InterruptedException | ExecutionException | JSONException e) {
e.printStackTrace();
}
}
}
EDIT Ok finally i solved my problem with your solution but now i have this problem :
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:873)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:215)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1481)
at android.view.View.dispatchRestoreInstanceState(View.java:14762)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3123)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3129)
at android.view.View.restoreHierarchyState(View.java:14740)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:475)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1329)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
To inflate fragments inside another fragment you need tu use getChildFragmentManager() instead of
myContext.getSupportFragmentManager().
EDIT:
Use FragmentStatePagerAdapter as follows:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
private List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
//Check if the list is empty before return the size
#Override
public int getCount() {
return mFragmentList != null ? mFragmentList.size() : 0;
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
#Override
public CharSequence getPageTitle(int position) {
if (!mFragmentTitleList.isEmpty()) {
return mFragmentTitleList.get(position);
}
return "";
}
}
Then in your fragment just add the fragments you want to show in the viewPager:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
...
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(SlideToutesPlaylist.newInstance(), getString(R.string.title));
adapter.addFragment(SlideToutesPlaylist.newInstance(), getString(R.string.title));
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);
I have a really basic app that has three fragments - fragments a,b and c, each of these fragments contains a piece of text that reads "I have been visited " + tallyVariable + " this many times".
I'm not entirely sure this is the correct way of doing it as I am new to app development and fairly new to the java language, but have attempted to give it a go.
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.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends FragmentActivity {
//tally variables
public int numSwipes = 0;
public int numSwipes2 = 0;
public int numSwipes3 = 0;
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
}
class MyAdapter extends FragmentStatePagerAdapter{
// reference to MainActivity and variables
MainActivity mainActivity = new MainActivity();
int fragNumSwipes = mainActivity.numSwipes;
int fragNumSwipes2 = mainActivity.numSwipes2;
int fragNumSwipes3 = mainActivity.numSwipes3;
public MyAdapter(FragmentManager fm) {
super(fm);
}
//#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if(i==0)
{
fragment = new FragmentA();
fragNumSwipes++;
}
if(i==1)
{
fragment = new FragmentB();
fragNumSwipes2++;
}
if(i==2)
{
fragment = new FragmentC();
fragNumSwipes3++;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position){
if(position==0)
{
return "tab 1";
}
if(position==1)
{
return "tab 2";
}
if(position==2)
{
return "tab 3";
}
return null;
}
}
below is the code for one of the fragments (code for the rest of the fragments is identical).
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentA extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a,container,false);
}
// MyAdapter adapterVariables = new MyAdapter();
}
I have commented out the above variable declaration "adapterVariables", but when it is active, it will not let me create a reference to the MyAdapter class where the tally variables now exist? what am I missing, I think it expects something between the parenthesis?
MainActivity mainActivity = new MainActivity(); this does not create a reference to your MainActivity! The same goes for your fragments code. You are creating new instances of your classes. You can pass references in your constructors. But for your idea, you won't need this. Below, you can find a corrected version, if you have questions about it, feel free to ask!
public class MainActivity extends FragmentActivity {
//tally variables
private int numSwipes = 0;
private int numSwipes2 = 0;
private int numSwipes3 = 0;
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
//instead of increasing the number in the adapter, add a listener, since this is a better place to do it.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch(position){
case 0:
numSwipes++;
break;
case 1:
numSwipes2++;
break;
case 2:
numSwipes3++;
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position){
if(position==0)
{
return "tab 1";
}
if(position==1)
{
return "tab 2";
}
if(position==2)
{
return "tab 3";
}
return null;
}
}
In my app I want to use swipe views of four tabs inside a fragment. The four tabs are contains different fragments each and all the four fragments are sliding by swipe from right to left or vice versa. The fragments are working fine but the tabs are not visible within the fragment. Anyone have any solution for this. Thanks in advance :)
this is the main fragment which contains the tabs:-
public class DashboardTabFragment extends Fragment implements ActionBar.TabListener {
private static final String ARG_SECTION_NUMBER = "arg_section_number";
private String[] tabTitle = {"Cleanness", "Product Display", "Hygiene", "Asm Visits"};
public static DashboardTabFragment newInstance(int position) {
DashboardTabFragment fragment = new DashboardTabFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
return fragment;
}
private ViewPager viewPager;
public DashboardTabFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard_tab, container, false);
setHasOptionsMenu(true);
ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
assert actionBar != null;
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
TabPageAdapter tabPageAdapter = new TabPageAdapter(getActivity().getSupportFragmentManager(), getActivity());
viewPager.setAdapter(tabPageAdapter);
for (String aTabTitle : tabTitle)
actionBar.addTab(actionBar.newTab().setText(aTabTitle).setTabListener(this));
return rootView;
}
This is the adapter for fragments:-
public class TabPageAdapter extends FragmentPagerAdapter {
Context context;
public TabPageAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CleannessChartFragment(context);
case 1:
return new ProductDisplayChartFragment(context);
case 2:
return new HygieneChartFragment(context);
case 3:
return new AsmVisitsChartFragment(context);
}
return null;
}
#Override
public int getCount() {
return 4;
}
I found the solution. I used TabHost for tabs with viewpager.
This is my fragment :-
package com.itpp.trt;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TabHost;
public class DashboardTabFragment extends Fragment implements ViewPager.OnPageChangeListener {
private static final String ARG_SECTION_NUMBER = "arg_section_number";
private ViewPager mViewPager;
private TabHost tabHost;
private String[] tabSpec = {"Tab_1", "Tab_2", "Tab_3", "Tab_4"};
private String[] tabTitle = {"Cleanness", "Product Display", "Hygiene", "Asm Visits"};
private TabHost.TabContentFactory mFactory = new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
View v = new View(getActivity());
v.setMinimumHeight(0);
return v;
}
};
public static DashboardTabFragment newInstance(int position) {
DashboardTabFragment fragment = new DashboardTabFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
return fragment;
}
public DashboardTabFragment() {
tabHost = null;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard_tab, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.pager);
mViewPager.setAdapter(new TabPageAdapter(getChildFragmentManager(), getActivity()));
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
tabHost.setup();
mViewPager.setOnPageChangeListener(this);
for (int i = 0; i < tabSpec.length; i++) {
tabHost.addTab(tabHost.newTabSpec(tabSpec[i]).setIndicator(tabTitle[i]).setContent(mFactory));
}
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
if (tabId.equals("Tab_1")) {
mViewPager.setCurrentItem(0);
} else if (tabId.equals("Tab_2")) {
mViewPager.setCurrentItem(1);
} else if (tabId.equals("Tab_3")) {
mViewPager.setCurrentItem(2);
} else if (tabId.equals("Tab_4")) {
mViewPager.setCurrentItem(3);
}
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MyActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onDetach() {
super.onDetach();
}
}
This is my tabpager adapter :-
package com.itpp.trt;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by biswajit on 28-11-14.
*/
public class TabPageAdapter extends FragmentStatePagerAdapter{
Context context;
public TabPageAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CleannessChartFragment(context);
case 1:
return new ProductDisplayChartFragment(context);
case 2:
return new HygieneChartFragment(context);
case 3:
return new AsmVisitsChartFragment(context);
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
Hope this helps other. Thanks :)
I am trying to create a fragment that would have a ViewPager. When the said fragment is called and committed, it only displays the first image and it is not swipable. Any thoughts how to achieve this?
Here is the Fragment
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HowToFragment extends Fragment {
private ViewPager mViewPager;
private MyAdapter mAdapter;
private int[] image_id = {R.drawable.image_1, R.drawable.image_2, R.drawable.image_3};
private static int image_pos = 0;
public static Fragment newInstance(int pos){
image_pos = pos;
return new HowToFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_how_to_image, container, false);
v.setBackgroundResource(image_id[image_pos]);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewPager = new ViewPager(getActivity());
mViewPager.setId(R.id.viewPager_howto);
FragmentManager fm = getFragmentManager();
mAdapter = new MyAdapter(fm);
new setAdapterTask().execute();
}
private class setAdapterTask extends AsyncTask<Void,Void,Void>{
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
mViewPager.setAdapter(mAdapter);
}
}
private class MyAdapter extends FragmentStatePagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
return image_id.length;
}
#Override
public Fragment getItem(int position) {
return HowToFragment.newInstance(position);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.remove((Fragment) object);
ft.commit();
super.destroyItem(container, position, object);
}
}
}
I doubt you are trying to run this app in Android version less than Honeycomb. What you are trying to achieve is nested fragments. Nested fragment support is available only since jellybean 4.2