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).
Related
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");
}
}
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
I've been trying to create a simple Horizontal scrolling option.
I have 2 ListFragments, which I would like to scroll between.
I'm getting a "Source Not Found" error when returning the View from onCreateView function.
This is my MainActivity Class:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.app.FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, android.app.FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.app.FragmentTransaction fragmentTransaction) {
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
Fragment a;
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new FragmentA();
default:
return new FragmentB();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Section " + (position + 1);
}
}
}
This is one of my ListFragment class (the second is the same but different name & layout file):
public class FragmentA extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.favorites_layout, container, false);
updateStationsView(0);
return rootView;
}
}
updateStationView is a function that populates the List. removing it did not help, so I figured it's harmless.
The error is thrown right after the:
return rootView;
which returns to the onCreate functions of MainActivity.
When I'm changing the ListFragment to be a simple Fragment it works. I think I'm lacking some knowledge to figure this one out. I really want to use ListFragment...
Can someone please try an help ?
Many thanks for your efforts.
Adding the XML files:
activity_main.xml:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
favorites_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
I im quite sure the issue is that your custom layout for the ListFragment does not contain a ListView. These lines of code are causing the error because you need to have a ListView inside your "favourites_layout" .xml file.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.favorites_layout, container, false);
updateStationsView(0);
return rootView;
}
ListFragment has a default layout that consists of a single list view.
However, if you desire, you can customize the fragment layout by
returning your own view hierarchy from onCreateView(LayoutInflater,
ViewGroup, Bundle). To do this, your view hierarchy must contain a
ListView object with the id "#android:id/list" (or list if it's in
code)
So your layout could for example look like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
See here for more:
http://developer.android.com/reference/android/app/ListFragment.html
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.
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.