Android ViewPager Displaying TextView in Layout - android

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.

Related

How to add swipe tab feature with existing FragmentTabHost?

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.

Android FragmentActivity How to refresh fragment when it become visible

I'm developing an application for Android and need some help implementing Tabs
I need it to be compatible with android 2.2
I started to implement Tabs but now i dont know if it was the best idea
What I want is basically:
I want to open a activity where it will have the tabs
In each of the Tab, I want to load content dinamicly, like the play store apk:
My main problem is:
I have created a AsyncTask with an ProgressDialog for each fragment to load the data and show it on the fragment, but when the fragment activity open, it initialize all the tabs and makes to load all the fragments at the same time.
I want to load the Tab content only when the Tab becomes visible, because the user may want to see only one tab, so no need to get the other Tabs
How should I do that?
Should I use TabFragments or others methods?
My current Tab activiy is:
public class Tabs2 extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener{
ViewPagerAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
private String interID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Infla o layout
setContentView(R.layout.tablayout);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
// Fragments and ViewPager Initialization
List<Fragment> fragments = getFragments();
pageAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments);
mViewPager.setAdapter(pageAdapter);
mViewPager.setOnPageChangeListener(Tabs2.this);
}
// Method to add a TabHost
private static void AddTab(Tabs2 activity, TabHost tabHost, TabHost.TabSpec tabSpec) {
tabSpec.setContent(activity.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);
}
// 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 onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageSelected(int arg0) {
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// Put here your Fragments
fList.add(Fragment.instantiate(this, TabFragmentA.class.getName()));
fList.add(Fragment.instantiate(this, TabFragmentB.class.getName()));
fList.add(Fragment.instantiate(this, TabFragmentC.class.getName()));
return fList;
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// Put here your Tabs
Tabs2.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Detalhes"));
Tabs2.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Comentários"));
Tabs2.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("cenas"));
mTabHost.setOnTabChangedListener(this);
}
// Um simples factory que retorna View para o TabHost
class MyTabFactory implements TabContentFactory {
private final Context mContext;
public MyTabFactory(Context context) {
mContext = context;
}
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
}
The ViewPagerAdatper:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments;
public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
mFragments = fragments;
}
#Override
public Fragment getItem(int i) {
return mFragments.get(i);
}
#Override
public int getCount() {
return mFragments.size();
}
}
The XML for the Tabs activiy
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="35dp"
android:orientation="horizontal"
android:gravity="bottom"
android:padding="0dip" />
<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/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:isScrollContainer="true"
android:scrollbars="vertical" />
</LinearLayout>
</TabHost>
For each Tab I used Fragments
public class TabFragmentA extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
// HERE I Call the AsyncTask and return the data with the layout
return (RelativeLayout) inflater.inflate(R.layout.layout_a, container, false);
}
}
since you are using a viewpager this is how a viewpager works and for good reason. A view pager by default loads the previous, current and next tab so that the content is ready when the user gets to the tab. you cannot change the viewpager to only load one page at a time.
If you notice this is exactly how the play store works

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 gui with actionbar, fragments and viewpager

Hello!
I've been programming for a long time but just started developing for android, which seems to be quite different from c++ to say at least...
Anyway, I'm trying to implement a gui with some tabs, that should be able to change tab on swipe left/right. The tabs are implemented with actionbar (or ActionBarSherlock to be precise), the swiping with ViewPager from the support lib. The individual tabs are fragments (SherlockFragment:s that is). At the bottom there should be a statusbar of some kind just displaying some text.
The problem I'm having is that the tabs are never shown. I see the actionbar on top with logo/title, with a tab list under it. At the bottom of the screen I see the statusbar-text, but nothing else.
If I uncomment the line //context.setContentView(pager); in SwipeBar() constructor, the content of the tabs are shown, but then the statusbar is not shown. (This line feels really wrong to have here anyway but I can't figure out how to get some content in my tabs without it.)
I've tried everything I can think of. I've read everything I could find about it and tried allot of different examples on how to do each functionality by itself. But combining them... I just can't get this to work. I'd really appreciate your help!
My main (activity) class:
Main.java
public class Main extends SherlockFragmentActivity {
private SwipeBar tabs;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tabs = new SwipeBar(this, R.id.pager);
tabs.add(One.class, "one", null);
tabs.add(Two.class, "two", null);
tabs.add(Three.class, "three", null);
}
}
This is my class that implements actionbar/viewpager/fragments:
SwipeBar.java
public class SwipeBar extends FragmentPagerAdapter implements OnPageChangeListener,
TabListener {
private final ActionBar bar;
private final SherlockFragmentActivity ctx;
private final ViewPager pager;
private final ArrayList<TabInfo> tabs;
public SwipeBar(final SherlockFragmentActivity context, final int viewPagerId) {
super(context.getSupportFragmentManager());
bar = context.getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
pager = new ViewPager(context);
pager.setId(viewPagerId);
pager.setAdapter(this);
pager.setOnPageChangeListener(this);
ctx = context;
// context.setContentView(pager);
tabs = new ArrayList<TabInfo>();
}
public void add(final Class<?> clss, final int tabHeaderStringId, final Bundle args) {
final ActionBar.Tab tab = bar.newTab();
final TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setText(tabHeaderStringId);
tab.setTabListener(this);
tabs.add(info);
bar.addTab(tab);
notifyDataSetChanged();
}
#Override
public int getCount() {
return tabs.size();
}
#Override
public Fragment getItem(final int pos) {
final TabInfo info = tabs.get(pos);
return Fragment.instantiate(ctx, info.clss().getName(), info.args());
}
public void onPageScrolled(final int arg0, final float arg1, final int arg2) {}
public void onPageScrollStateChanged(final int arg0) {}
public void onPageSelected(final int pos) {
bar.setSelectedNavigationItem(pos);
}
public void onTabReselected(final Tab tab, final FragmentTransaction ft) {}
public void onTabSelected(final Tab tab, final FragmentTransaction ft) {
final TabInfo tag = (TabInfo)tab.getTag();
for(int i = 0; i < tabs.size(); i++)
if(tabs.get(i) == tag) pager.setCurrentItem(i);
}
public void onTabUnselected(final Tab tab, final FragmentTransaction ft) {}
}
The main layout:
Main.xml
<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" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0px">
</android.support.v4.view.ViewPager>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#33FF0000"
android:gravity="center"
android:layout_weight="0"
android:text="statusbar">
</TextView>
</LinearLayout>
And the code for the three pages:
One/Two/Three.xml/java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/one"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="this is tab one" />
</LinearLayout>
public class One extends SherlockFragment {
#Override
public View onCreateView(final LayoutInflater inflater,
final ViewGroup container, final Bundle savedInstanceState) {
return (LinearLayout)inflater.inflate(R.layout.one, container, false);
}
}
Okay, I finally solved it. The above code came from trying to add ViewPager functionality to the tabs I had done. I started over and implemented a regular ViewPager (like in the various examples out there) and then added an ActionBar. The actual fragment content is now in the ViewPager and the ActionBar tabs is empty, but set through the ViewPager callbacks to indicate the current one.
I have still no clue what was wrong with the original attempt though...

Android ViewPager - How to add buttons to the pages?

I am following this link to do a ViewPager http://blog.stylingandroid.com/archives/537
I managed to get the various pages out. But how do I populate or fill these pages with buttons?
instantiateItem()
This creates the view for a given position. For a
real application we would use a Fragment here, or inflate a layout,
but to keep the example simple we create a TextView, set the text to
the correct value from our titles array, and add it to the ViewPager
I want to have different button functions on different pages. How do I go about doing this? By using different layout? How do I put the layout within the page (is this what you call inflat)?
EDIT:
I have the main.xml which consists of the ViewPager
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<com.viewpagerindicator.TitlePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
I have several other xml which consists of buttons which I want to inflate it into the different pages of the ViewPage. Example of an 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:orientation="vertical" >
<Button android:layout_width="match_parent" android:text="Button 1" android:onClick="onClick" android:id="#+id/button1" android:layout_height="100dp"></Button>
<Button android:text="Button 2" android:onClick="onClick" android:id="#+id/button2" android:layout_width="match_parent" android:layout_height="100dp"></Button>
<Button android:text="Button 3" android:onClick="onClick" android:id="#+id/button3" android:layout_width="match_parent" android:layout_height="100dp"></Button>
<Button android:text="Button 4" android:onClick="onClick" android:id="#+id/button4" android:layout_width="match_parent" android:layout_height="100dp"></Button>
<Button android:text="Button 5" android:onClick="onClick" android:id="#+id/button5" android:layout_height="match_parent" android:layout_width="match_parent"></Button>
</LinearLayout>
In the ViewPagerAdapter.java, I managed to inflate the various XML into the pages.
#Override
public Object instantiateItem( View pager, int position )
{
//Inflate the correct layout
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//layouts[] is an int[] that points to resources such as R.layout.start_page
View inflatedView = layoutInflater.inflate(layouts[position], null);
((ViewPager)pager).addView(inflatedView,0);
return inflatedView;
}
And this needs to be changed to prevent error.
#Override
public void destroyItem( View pager, int position, Object view )
{
((ViewPager)pager).removeView( (View)view );
}
Now, I have multiple buttons on different pages. How do I programme the ONCLICK function of the different buttons on the different pages? Can this work?
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
// do something
break;
case R.id.button2:
// do something
break;
case R.id.button3:
// do something
break;
case R.id.button4:
// do something
break;
case R.id.button5:
// do something
break;
}
}
Here is an example of inflating/programmatically adding views with buttons:
#Override
//Instantiate items based on corresponding layout IDs that were passed in
public Object instantiateItem(View container, int position)
{
//Inflate the correct layout
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//layouts[] is an int[] that points to resources such as R.layout.start_page
View inflatedView = layoutInflater.inflate(layouts[position], null);
((ViewPager)container).addView(inflatedView,0);
//If you can't/don't want to have the above inflated layout include everything up front, you can add them now...
LinearLayout ll = (LinearLayout)inflatedView.findViewById(R.id.linearLayout1);
Button newButton = new Button(context);
newButton.setText(R.string.button_text);
ll.addView(newButton);
return inflatedView;
}
I recently set up a system with a ViewPager. I use actionbar tabs (with compatibility library), a TabAdapter and ViewPager. Each tab is its own fragment and added into the bar via the main activity. Here is some of the key code:
public class Polling extends FragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getActionBar();
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);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
}
And the adapter:
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(FragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getActionBar();
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 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) {
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) {}
#Override
public void onTabSelected(Tab tab, android.app.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, android.app.FragmentTransaction ft) {}
}
And here's a class that makes buttons and widgets on each tab:
public class EconFragment extends SherlockFragment {
Polling activity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
activity = (Polling)getActivity();
View v = inflater.inflate(R.layout.categoryfragment, container, false);
this.mainLayout = v;
return v;
}
So long as you edit the XML file that is inflated in the above code (categoryfragment.xml), each tab will load whatever you want to put on the page (TextView, Button, etc).

Categories

Resources