How to add swipe tab feature with existing FragmentTabHost? - android

I am using FragmentTabHost in my app. It is working perfectly well. I have two tabs, which are opened by clicking on the top. Now, I want to add swipe feature in this. I am wondering whether I should use a different approach for the same.
MainActivity:
package com.example.shiza.callhistorycontrol;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private FragmentTabHost mTabHost;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setting up a toolbar for the navigation purpose.
toolbar = (Toolbar)findViewById(R.id.app_bar);
toolbar.setTitle(" Call History Control");
toolbar.setLogo(R.mipmap.ic_launcher);
setSupportActionBar(toolbar);
// The fragments management is done here
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("HOME"),
Home.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("ABOUT APP"),
Home.class, null);
}
}
main xml:
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- the app bar customized-->
<include
android:id="#+id/app_bar"
layout="#layout/app_bar"
/>
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
<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="wrap_content"/>
</android.support.v4.app.FragmentTabHost>
Please provide me any links or any suggestions?

Here is an example that I wrote creates TabHost with swipe feature:
First the main fragment that holds the adapter and add tabs with (two childes fragments).
public class MyFragment extends Fragment
{
private TabHost mTabHost;
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
public MyFragment() {
}
#Override
public void onCreate(Bundle instance)
{
super.onCreate(instance);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main, container, false);
mTabHost = (TabHost) v.findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager) v.findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(getActivity(), mTabHost, mViewPager);
// Here we load the content for each tab.
mTabsAdapter.addTab(mTabHost.newTabSpec("simple").setIndicator("HOME"), FirstPage.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("simple").setIndicator("HOME"), SecondPage.class, null);
return v;
}
#Override
public void onResume() {
super.onResume();
}
public static class TabsAdapter extends FragmentStatePagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener
{
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo
{
private final String tag;
private final Class<?> clss;
private final Bundle args;
TabInfo(String _tag, Class<?> _class, Bundle _args)
{
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory
{
private final Context mContext;
public DummyTabFactory(Context context)
{
mContext = context;
}
public View createTabContent(String tag)
{
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager)
{
super(activity.getSupportFragmentManager());
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args)
{
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
mTabs.add(info);
mTabHost.addTab(tabSpec);
notifyDataSetChanged();
}
#Override
public int getCount()
{
return mTabs.size();
}
#Override
public Fragment getItem(int position)
{
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
public void onTabChanged(String tabId)
{
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
public void onPageSelected(int position)
{
// Unfortunately when TabHost changes the current tab, it kindly
// also takes care of putting focus on it when not in touch mode.
// The jerk.
// This hack tries to prevent this from pulling focus out of our
// ViewPager.
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
}
public void onPageScrollStateChanged(int state)
{
}
}
Then create another two fragments that represent each tab and call them:
FirstPage
SecondPage
link those to xml files, call new MyFragment and you are good to go.

Related

ViewPager not loading middle page correctly

I have a fragment that has a TabHost inside of it with 3 tabs. My main activity has a navigation drawer and when the option with a tab layout inside is selected it loads all 3 tabs correctly the first time, but if I open the drawer and click the option with tabs again, the middle option never shows up. I also constantly get this message while debugging as well.
W/FragmentManager﹕ moveToState: Fragment state for PageThreeFragment{426c2ad8 #3 id=0x7f0f0063 android:switcher:2131689571:2} not updated inline; expected state 3 found 2
I'm hoping someone can help me resolve this bug because the solution is evading me.
Fragment with tab layout inside code
package com.robotca.ControlApp.Fragments;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabWidget;
import java.util.ArrayList;
import com.robotca.ControlApp.R;
public class HelpFragment extends Fragment
{
private TabHost mTabHost;
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
public HelpFragment() {
}
#Override
public void onCreate(Bundle instance)
{
super.onCreate(instance);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_help, container, false);
mTabHost = (TabHost) v.findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager) v.findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(getActivity(), mTabHost, mViewPager);
// Here we load the content for each tab.
mTabsAdapter.addTab(mTabHost.newTabSpec("one").setIndicator("Setup"), PageOneFragment.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("two").setIndicator("Using"), PageTwoFragment.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("three").setIndicator("FAQ"), PageThreeFragment.class, null);
return v;
}
public static class TabsAdapter extends FragmentPagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener
{
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo
{
private final String tag;
private final Class<?> clss;
private final Bundle args;
TabInfo(String _tag, Class<?> _class, Bundle _args)
{
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory
{
private final Context mContext;
public DummyTabFactory(Context context)
{
mContext = context;
}
public View createTabContent(String tag)
{
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager)
{
super(activity.getSupportFragmentManager());
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args)
{
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
mTabs.add(info);
mTabHost.addTab(tabSpec);
notifyDataSetChanged();
}
#Override
public int getCount()
{
return mTabs.size();
}
#Override
public Fragment getItem(int position)
{
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
public void onTabChanged(String tabId)
{
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
public void onPageSelected(int position)
{
// Unfortunately when TabHost changes the current tab, it kindly
// also takes care of putting focus on it when not in touch mode.
// The jerk.
// This hack tries to prevent this from pulling focus out of our
// ViewPager.
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
}
public void onPageScrollStateChanged(int state)
{
}
}
}
xml layout
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</TabHost>
Fragment code for the sliding tab options (all 3 are basically the same)
public class PageOneFragment extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.pageone_fragment, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
}
#Override
public void onStart()
{
super.onStart();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onDestroy()
{
super.onDestroy();
}
}
The layout for all 3 fragments is a simple TextView
gradle file
dependencies {
// compile project(':control_app_lib')
compile fileTree(dir: 'libs', include: ['*.jar'])
///////////////
compile 'org.ros.android_core:android_10:[0.2,0.3)'
compile 'org.ros.android_core:android_15:[0.2,0.3)'
compile 'com.github.rosjava.android_extras:gingerbread:[0.2,0.3)'
compile 'org.ros.rosjava_messages:tf2_msgs:[0.5,0.6)'
compile 'com.google.code.gson:gson:2.5'
compile 'com.android.support:support-v13:23.0.1'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:cardview-v7:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.1'
compile 'org.osmdroid:osmdroid-android:5.0.1'
compile 'org.slf4j:slf4j-android:1.6.1-RC1'
compile 'com.github.MKergall.osmbonuspack:OSMBonusPack:v5.7'
compile 'com.android.support:support-v4:23.0.1'
compile 'com.github.amlcurran.showcaseview:library:5.4.1'
}
There is a issue reported in https://code.google.com/p/android/issues/detail?id=202037 related to ViewPager + FragmentStatePagerAdapter with Nested fragments.
Try downgrading your support library version to 23.0.1. With 23.1.1 and 23.2.0 seems to exist this bug.
Hope this helps!!
Reducing the version numbers of every support library to 23.0.1 did the trick for me.
build.gradle file -
compile 'com.android.support:design:23.0.1'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:support-v13:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.1'
I hope this is what you are looking for.

Tabs execute the codes present in their next fragments in android

I am trying to implement Tabs with swipe using ViewPager and 4 Fragments. When I swipe the tabs the respective xml layouts of the fragmnets are displayed correctly on each tab but the code of the fragments are not executed correctly.
eg-The following tabs have the respective fragments in it.
Tab0-ButtonFragment
public class ButtonFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_button, container, false);
Log.i("inside", "button fragment");
return rootView;
}
Tab1-ImageFragment
public class ImageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image, container, false);
Log.i("inside", "image fragment");
return rootView;
}
Tab2-TextFragment
public class TextFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_text, container, false);
Log.i("inside", "text fragment");
return rootView;
}
Tab3-Test
public class Test extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.temp, container, false);
Log.i("inside", "tessssssssst fragment");
return rootView;
}
When the tabs are displayed
I get the log message for tab0 and tab1 simultaneously. Then after swiping and going to tab1 i get the log message for tab2. After swiping to tab2 i get log message for tab 3 and when tab 3 is reached no log message is dispalyed. Can anyone tell me how can I execute the respective codes for the respective tabs? My remaining codes are as below:
public class TabsPagerAdapter extends FragmentPagerAdapter { //Update - code formatting
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem( int index) {
Log.i("index", "" + index);
switch (index) {
case 0:
// Top Rated fragment activity
return new ButtonFragment();
case 1:
// Games fragment activity
return new ImageFragment();
case 2:
// Movies fragment activity
return new TextFragment();
case 3:
return new Test();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
MainActivity
public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {
private TabsPagerAdapter mAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
// Fragments and ViewPager Initialization
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(MainActivity.this);
}
// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(activity));
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("ButtonTab").setIndicator("ButtonTab"));
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("ImageTab").setIndicator("ImageTab"));
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("TextTab").setIndicator("TextTab"));
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("TestingTab").setIndicator("TestingTab"));
mTabHost.setOnTabChangedListener(this);
}
This is default behaviour of viewpager you can not change it as viewpager creates fragments so that the views exist, so the user can swipe between them, so that the old view sliding off the screen and the new view sliding onto the screen. You can write your code like this
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
Log.i("inside", "button fragment");
}else{
// fragment is not visible
}
}
so that when fragment is visible your code execute
When change your tab recall your corresponding fragment.
Try this it will help you
Create TabFragment.java
public class TabFragment extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
private TabHost tabHost;
private int currentTab = 0;
private SwipeDisableViewPager viewPager;
protected TabPagerAdapter pageAdapter;
private List<Fragment> fragments;
private final int TAB_BUTTON=0,TAB_IMAGE=1,TAB_TEXT=2,TAB_TEST=3;
#SuppressWarnings("unchecked")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tabhost, null);
viewPager = (SwipeDisableViewPager) view.findViewById(R.id.viewpager);
tabHost = (TabHost) view.findViewById(android.R.id.tabhost);
viewPager.addOnPageChangeListener(this);
fragments = new ArrayList<>();
fragments.add(new ButtonFragment());
fragments.add(new ImageFragment());
fragments.add(new TextFragment());
fragments.add(new Test());
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
pageAdapter = new TabPagerAdapter(getChildFragmentManager(), fragments, getArguments());
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
viewPager.setOffscreenPageLimit(3);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.home, R.drawable.menu_home_bg));
tabHost.addTab(newTab(R.string.likes, R.drawable.menu_likes_bg));
tabHost.addTab(newTab(R.string.matches, R.drawable.menu_matches_bg));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
}
tabHost.setOnTabChangedListener(this);
tabHost.setCurrentTab(currentTab);
}
private View getTabIndicator(Context context, int title, int icon) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_view, null);
ImageView iv = (ImageView) view.findViewById(R.id.imageView);
iv.setImageResource(icon);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText(title);
return view;
}
private TabSpec newTab(int tabValue, int icon) {
TabSpec tabSpec = tabHost.newTabSpec(getString(tabValue));
tabSpec.setIndicator(getTabIndicator(tabHost.getContext(), tabValue, icon));
tabSpec.setContent(new Dummy(getActivity()));
return tabSpec;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int currentPosition, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
if (position == 0)
viewPager.setSwipeEnabled(false);
else
viewPager.setSwipeEnabled(true);
tabHost.setCurrentTab(position);
if (listener != null)
listener.onTabChanged(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
switch(currentTab){
case TAB_BUTTON:
((ButtonFragment) fragments.get(currentTab)).recall();
break;
case TAB_IMAGE:
((ImageFragment) fragments.get(currentTab)).recall();
break;
case TAB_TEXT:
((TextFragment) fragments.get(currentTab)).recall();
break;
case TAB_TEST:
((Test) fragments.get(currentTab)).recall();
break;
}
}
create tab_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/menu_bg"
android:fadingEdge="none"
android:gravity="center"
android:showDividers="none"
android:tabStripEnabled="false" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<com.mobellotech.shift.Widget.SwipeDisableViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#FFFFFF" />
</LinearLayout>
</TabHost>
Create tab_view.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView"
android:layout_width="45dp"
android:layout_height="45dp"
android:contentDescription="#string/menu_icon" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Create TabPagerAdaper
public class TabPagerAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;
public TabPagerAdapter(FragmentManager fm, List<Fragment> fragments,
Bundle args) {
super(fm);
this.fragments = fragments;
this.args = args;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Create MainActivity.java
public class MainActivity extends AppCompatActivity {
protected TabFragment tabFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabFragment = new TabFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, tabFragment).commit();
}
}
Create activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.DrawerLayout>
Finally add the recall method in your fragment class like this
public class ButtonFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_button, container, false);
Log.i("inside", "button fragment");
return rootView;
}
public void recall() {
Log.i("inside", "button fragment");
}
}

Tab inside fragment in Android

I am Trying to add a TabHost Inside a Fragment like in example, getting NullPointerException when calling
mTabHost.setup()
what can be the problem ? code below
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabs_layout,container,false);
mTabHost = (FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.tabcontent);
mTabHost.addTab(mTabHost.newTabSpec("fragmentb").setIndicator("tab1"),
Fragment1.class, null);
mTabHost.addTab(mTabHost.newTabSpec("fragmentc").setIndicator("tab2"),
Fragment2.class, null);
return rootView;
}
XML:
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
This following code is an example I use:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_tab_destaques, container, false);
mTabHost = (TabHost) mView.findViewById(android.R.id.tabhost);
initialiseTabHost();
return mView;
}
private void initialiseTabHost() {
mTabHost.setup();
String title = "TITLE";
addTab(getActivity(), this.mTabHost, this.mTabHost.newTabSpec(title).setIndicator(title));
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(),
"fonts/Roboto-Bold.ttf");
for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
TextView tv = (TextView) mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
tv.setTextAppearance(getActivity(), android.R.style.TextAppearance_Medium);
tv.setTextColor(Color.WHITE);
tv.setTypeface(tf);
mTabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.selector_actionbar);
}
mTabHost.setOnTabChangedListener(this);
}
private static void addTab(Activity activity, TabHost tabHost, TabHost.TabSpec tabSpec) {
tabSpec.setContent(new InicialTabFactory(activity));
tabHost.addTab(tabSpec);
}
My fragment_tab_destaques.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<HorizontalScrollView
android:id="#+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:scrollbars="none"
android:background="#color/BlueViolet">
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundStacked="#color/white"
android:weightSum="2" />
</HorizontalScrollView>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</LinearLayout>
</TabHost>
</LinearLayout>
EDIT
InicialTabFactory.java:
public class InicialTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public InicialTabFactory(Context context) {
mContext = context;
}
#Override
public View createTabContent(String s) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
Solve your issue + a beautiful Material Design HERE
I have used Tab with viewPager inside fragment. This is my code :-
#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;
}
This is the layout file :-
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="0dp" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</TabHost>
Hope this helps you :)
my simple working example
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, ArtistsActivity.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("artists").setIndicator("Artists",
res.getDrawable(R.drawable.ic_tab_artists))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, AlbumsActivity.class);
spec = tabHost.newTabSpec("albums").setIndicator("Albums",
res.getDrawable(R.drawable.ic_tab_albums))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, SongsActivity.class);
spec = tabHost.newTabSpec("songs").setIndicator("Songs",
res.getDrawable(R.drawable.ic_tab_songs))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(2);
}
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" />
</LinearLayout>
</TabHost>
Try this..
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
tabHost = new FragmentTabHost(getActivity());
tabHost.setup(getActivity(), getChildFragmentManager(), R.layout.fragment_home);
Bundle arg1 = new Bundle();
arg1.putInt("Arg for Frag1", 1);
tabHost.addTab(tabHost.newTabSpec("Tab1").setIndicator("tab1"),
Tab1Fragment.class, arg1);
Bundle arg2 = new Bundle();
arg2.putInt("Arg for Frag2", 2);
tabHost.addTab(tabHost.newTabSpec("Tab2").setIndicator("tab2"),
Tab2Fragment.class, arg2);
Bundle arg3 = new Bundle();
arg3.putInt("Arg for Frag3", 3);
tabHost.addTab(tabHost.newTabSpec("Tab3").setIndicator("tab3"),
Tab3Fragment.class, arg3);
return tabHost;
}
[SOLVED] This is the solution that I want. There is a main fragment and its inside there are tabs. Solution is here
And the code is here for possible future broken link:
package com.example.android.apis.app;
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import java.util.ArrayList;
import com.example.android.apis.R;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
/**
* Sample fragment that contains tabs of other fragments.
*/
public class FragmentTabsFragment extends Fragment {
TabManager mTabManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTabManager = new TabManager(getActivity(), getChildFragmentManager(),
R.id.realtabcontent);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tabs_fragment, container, false);
TabHost host = mTabManager.handleCreateView(v);
mTabManager.addTab(host.newTabSpec("result").setIndicator("Result"),
FragmentReceiveResult.ReceiveResultFragment.class, null);
mTabManager.addTab(host.newTabSpec("contacts").setIndicator("Contacts"),
LoaderCursor.CursorLoaderListFragment.class, null);
mTabManager.addTab(host.newTabSpec("apps").setIndicator("Apps"),
LoaderCustom.AppListFragment.class, null);
mTabManager.addTab(host.newTabSpec("throttle").setIndicator("Throttle"),
LoaderThrottle.ThrottledLoaderListFragment.class, null);
return v;
}
#Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
mTabManager.handleViewStateRestored(savedInstanceState);
}
#Override
public void onDestroyView() {
super.onDestroyView();
mTabManager.handleDestroyView();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mTabManager.handleSaveInstanceState(outState);
}
/**
* This is a helper class that implements a generic mechanism for
* associating fragments with the tabs in a tab host. DO NOT USE THIS.
* If you want tabs in a fragment, use the support v13 library's
* FragmentTabHost class, which takes care of all of this for you (in
* a simpler way even).
*/
public static class TabManager implements TabHost.OnTabChangeListener {
private final Context mContext;
private final FragmentManager mManager;
private final int mContainerId;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private TabHost mTabHost;
private TabInfo mLastTab;
private boolean mInitialized;
private String mCurrentTabTag;
static final class TabInfo {
private final String tag;
private final Class<?> clss;
private final Bundle args;
private Fragment fragment;
TabInfo(String _tag, Class<?> _class, Bundle _args) {
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabManager(Context context, FragmentManager manager, int containerId) {
mContext = context;
mManager = manager;
mContainerId = containerId;
}
public TabHost handleCreateView(View root) {
if (mTabHost != null) {
throw new IllegalStateException("TabHost already set");
}
mTabHost = (TabHost)root.findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabHost.setOnTabChangedListener(this);
return mTabHost;
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
mTabs.add(info);
mTabHost.addTab(tabSpec);
}
public void handleViewStateRestored(Bundle savedInstanceState) {
if (savedInstanceState != null) {
mCurrentTabTag = savedInstanceState.getString("tab");
}
mTabHost.setCurrentTabByTag(mCurrentTabTag);
String currentTab = mTabHost.getCurrentTabTag();
// Go through all tabs and make sure their fragments match
// the correct state.
FragmentTransaction ft = null;
for (int i=0; i<mTabs.size(); i++) {
TabInfo tab = mTabs.get(i);
tab.fragment = mManager.findFragmentByTag(tab.tag);
if (tab.fragment != null && !tab.fragment.isDetached()) {
if (tab.tag.equals(currentTab)) {
// The fragment for this tab is already there and
// active, and it is what we really want to have
// as the current tab. Nothing to do.
mLastTab = tab;
} else {
// This fragment was restored in the active state,
// but is not the current tab. Deactivate it.
if (ft == null) {
ft = mManager.beginTransaction();
}
ft.detach(tab.fragment);
}
}
}
// We are now ready to go. Make sure we are switched to the
// correct tab.
mInitialized = true;
ft = doTabChanged(currentTab, ft);
if (ft != null) {
ft.commit();
mManager.executePendingTransactions();
}
}
public void handleDestroyView() {
mCurrentTabTag = mTabHost.getCurrentTabTag();
mTabHost = null;
mTabs.clear();
mInitialized = false;
}
public void handleSaveInstanceState(Bundle outState) {
outState.putString("tab", mTabHost != null
? mTabHost.getCurrentTabTag() : mCurrentTabTag);
}
#Override
public void onTabChanged(String tabId) {
if (!mInitialized) {
return;
}
FragmentTransaction ft = doTabChanged(tabId, null);
if (ft != null) {
ft.commit();
}
}
private FragmentTransaction doTabChanged(String tabId, FragmentTransaction ft) {
TabInfo newTab = null;
for (int i=0; i<mTabs.size(); i++) {
TabInfo tab = mTabs.get(i);
if (tab.tag.equals(tabId)) {
newTab = tab;
}
}
if (newTab == null) {
throw new IllegalStateException("No tab known for tag " + tabId);
}
if (mLastTab != newTab) {
if (ft == null) {
ft = mManager.beginTransaction();
}
if (mLastTab != null) {
if (mLastTab.fragment != null) {
ft.detach(mLastTab.fragment);
}
}
if (newTab != null) {
if (newTab.fragment == null) {
newTab.fragment = Fragment.instantiate(mContext,
newTab.clss.getName(), newTab.args);
ft.add(mContainerId, newTab.fragment, newTab.tag);
} else {
ft.attach(newTab.fragment);
}
}
mLastTab = newTab;
}
return ft;
}
}
}

Static button below Viewpager w/ tabs - Actionbarsherlock

So I'm trying to create a layout such that I would have a viewpager w/tabs at the top of the page, with a couple of static buttons at the bottom that do not move when I swipe across tabs. Seem to have hit a roadblock though, my fragments don't load and I lose swiping capability when I implement the following code. I'm new to Actionbarsherlock, not sure what the problem is, would appreciate any help. Thanks!
The java:
public class Main extends SherlockFragmentActivity {
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
TextView tabCenter;
TextView tabText;
Menu menu;
SubMenu subMenu1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter
.addTab(bar.newTab().setText("Tab 1"), Fragment1.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Tab 2"), Fragment2.class,
null);
mTabsAdapter.addTab(bar.newTab().setText("Tab 3"), Fragment3.class,
null);
}
public static class TabsAdapter extends FragmentPagerAdapter implements
ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(),
info.args);
}
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
public void onPageScrollStateChanged(int state) {
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}
The XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="4dip" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1" >
</android.support.v4.view.ViewPager>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center"
android:measureWithLargestChild="true"
android:orientation="horizontal" >
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example" >
</Button>
</LinearLayout>
</LinearLayout>
Check out the below links. Here defined the ways to implement the functionality which you need.
1) Link 1
2) Link 2
3) Link 3
4) Link 4
5) Link 5
I hope it will help you.

Android ViewPager Displaying TextView in Layout

I'm trying to set up a ViewPager with a number of layouts with 2 TextViews in each layout. I'm having trouble getting my TextViews to display properly when i run my app. My pager works fine but it's not displaying the Textviews i have in my XML layout.
Here's my code that I have in my PageAdapter
public class MyPageAdapter extends PagerAdapter {
public int getCount() {
return 31;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.main_menu;
break;
case 1:
resId = R.layout.article1;
break;
case 2:
resId = R.layout.article2;
break;
....
....
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
This is what I have for my XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" android:background="#drawable/background" android:clickable="true"
android:id="#+id/layout13"
android:weightSum="0">
<TextView
android:id="#+id/textView01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:padding="12dp"
android:text="#string/article13"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#000000" />
<TextView
android:id="#+id/textView02"
android:layout_width="match_parent"
android:layout_height="302dp"
android:gravity="center_vertical|center_horizontal"
android:text="#string/body13"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#000000" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#id/viewPager" >
</android.support.v4.view.ViewPager>
</LinearLayout>
I've tried Moving the around in my XML layout to right underneath my LinearLayout and i get the full screen but all my text disappears. It's probably something simple i'm missing but any help on this would be greatly appreciated!
You only need one ViewPager. My app has 9 fragments and one activity. The viewpager is declared once in main.xml. Here's what the important code looks like:
public class Polling extends SherlockFragmentActivity implements OnMenuItemClickListener {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
//here's the code that makes a tab, adds it to the actionbar, adds a tabadapter, and coordinates the viewpager:
bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
So that's my main class. You'll lose I never actually directly employ the entire main.xml: the Content View gets set to the ViewPager rather than a layout. Then, inside my main activity, I have an inner class that handles the ViewPager going left/right, as well as the management of my actionBar tabs. But it doesn't sound like you are using tabs, so this next bit of code may not be that helpful:
public static class TabsAdapter extends FragmentPagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
public int getCount() {
return mTabs.size();
}
public SherlockFragment getItem(int position) {
TabInfo info = mTabs.get(position);
return (SherlockFragment)Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
//Log.v(TAG, "clicked");
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {}
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {}
}
}
I would try placing your ViewPager above the textViews, nested directly beneath the LinearLayout. I'm sorry I can't be of more help than that - my experience with ViewPager has been alongside a TabAdapter/actionBar tabs.
Here's the code to my Pager:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
All of the rest of my interface comes from other tabs, so this is the entirety of my main.xml. Basically I'm posting this to say that I've got my viewpager as the sole child widget inside a linear layout, and it manages the whole screen.

Categories

Resources