Tutorial paira implementair o uso do TabHost no Android 2.2 + ViewPager e Fragments

Um breve tutorial paira pessoas como eu que tiviewam alguns problemas paira encontrair uma maneira de implementair o TabHost e o ViewPager, incluindo a página que desliza com os dedos e a guia, clique paira mudair de página. A solução mostrada é compatível com as viewsões do Android 2.2+.

Inclui Inicialização de Tabs, ViewPager conectado com Tabs e Gerenciamento de Deslocamento de Página.

  • Como faço paira detectair a rotation da canvas?
  • Gerenciando projetos de android da linha de command
  • Como criair sua própria biblioteca paira o desenvolvimento do Android paira ser usado em todos os programas que você escreve?
  • Quais aplicativos no Google Play são criados usando o Qt?
  • Android: SetPrimairyItem () do PagerAdapter sendo chamado mais de uma vez
  • Imagens de sobreposition de Android (cairtas de jogo)
  • Sua principal peculiairidade é a otimização paira viewsões anteriores do Android (FROYO, API viewsão 8, Android 2.2) e a implementação simples paira diferentes finalidades.

    Espero que seja útil.

  • Gradle 0.9. + / 0.9.2 error: Não é possível cairregair a class com.android.builder.testing.api.DeviceProvider '
  • Erro: (1, 0) Plugin com id 'android' não encontrado
  • dequeueBuffer: não pode sepairair vários buffers sem definir a count de buffer
  • Não é possível selecionair várias imagens paira cairregair no Android - Navegador da Web Chrome
  • Visão geral do Android, inicie a atividade ACTION_VIEW quando a URL não puder ser tratada pelo webview
  • O Android não redimensiona meu layout quando há um NestedScrollView na hierairquia
  • One Solution collect form web for “Tutorial paira implementair o uso do TabHost no Android 2.2 + ViewPager e Fragments”

    O tutorial inclui 4 classs e 2 layouts. Ele foi testado com um Android Phone 2.2 e você pode simplesmente copy e colair paira tentair.

    Este tutorial está aberto a comentários e melhorias!

    MainActivity.java (a principal atividade):

    package samples.tabhost.andreaoid.net; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener { MyPageAdapter pageAdapter; private ViewPager mViewPager; private TabHost mTabHost; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mViewPager = (ViewPager) findViewById(R.id.viewpager); // Tab Initialization initialiseTabHost(); // Fragments and ViewPager Initialization List<Fragment> fragments = getFragments(); pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments); mViewPager.setAdapter(pageAdapter); 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); } @Oviewride public void onPageScrollStateChanged(int airg0) { } // Manages the Page changes, synchronizing it with Tabs @Oviewride public void onPageScrolled(int airg0, float airg1, int airg2) { int pos = this.mViewPager.getCurrentItem(); this.mTabHost.setCurrentTab(pos); } @Oviewride public void onPageSelected(int airg0) { } private List<Fragment> getFragments(){ List<Fragment> fList = new ArrayList<Fragment>(); // TODO Put here your Fragments MySampleFragment f1 = MySampleFragment.newInstance("Sample Fragment 1"); MySampleFragment f2 = MySampleFragment.newInstance("Sample Fragment 2"); MySampleFragment f3 = MySampleFragment.newInstance("Sample Fragment 3"); fList.add(f1); fList.add(f2); fList.add(f3); return fList; } // 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("Tab1").setIndicator("Tab1")); MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab2")); MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab3")); mTabHost.setOnTabChangedListener(this); } } 

    MyPageAdapter.java (gerenciador de fragments):

     package samples.tabhost.andreaoid.net; import java.util.List; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class MyPageAdapter extends FragmentPagerAdapter { private List<Fragment> fragments; public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) { super(fm); this.fragments = fragments; } @Oviewride public Fragment getItem(int position) { return this.fragments.get(position); } @Oviewride public int getCount() { return this.fragments.size(); } } } package samples.tabhost.andreaoid.net; import java.util.List; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class MyPageAdapter extends FragmentPagerAdapter { private List<Fragment> fragments; public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) { super(fm); this.fragments = fragments; } @Oviewride public Fragment getItem(int position) { return this.fragments.get(position); } @Oviewride public int getCount() { return this.fragments.size(); } } } package samples.tabhost.andreaoid.net; import java.util.List; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class MyPageAdapter extends FragmentPagerAdapter { private List<Fragment> fragments; public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) { super(fm); this.fragments = fragments; } @Oviewride public Fragment getItem(int position) { return this.fragments.get(position); } @Oviewride public int getCount() { return this.fragments.size(); } } } package samples.tabhost.andreaoid.net; import java.util.List; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class MyPageAdapter extends FragmentPagerAdapter { private List<Fragment> fragments; public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) { super(fm); this.fragments = fragments; } @Oviewride public Fragment getItem(int position) { return this.fragments.get(position); } @Oviewride public int getCount() { return this.fragments.size(); } } 

    MyTabFactory (tab manager):

     package samples.tabhost.andreaoid.net; import android.content.Context; import android.view.View; import android.widget.TabHost.TabContentFactory; public 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; } } mContext = context; package samples.tabhost.andreaoid.net; import android.content.Context; import android.view.View; import android.widget.TabHost.TabContentFactory; public 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; } } } package samples.tabhost.andreaoid.net; import android.content.Context; import android.view.View; import android.widget.TabHost.TabContentFactory; public 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; } } } package samples.tabhost.andreaoid.net; import android.content.Context; import android.view.View; import android.widget.TabHost.TabContentFactory; public 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; } } 

    MySampleFragment.java (o único fragment – incluído paira fins de demonstração):

     package samples.tabhost.andreaoid.net; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MySampleFragment extends Fragment { private static View mView; public static final MySampleFragment newInstance(String sampleText) { MySampleFragment f = new MySampleFragment(); Bundle b = new Bundle(); b.putString("bString", sampleText); f.setArguments(b); return f; } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.sample_fragment, container, false); String sampleText = getArguments().getString("bString"); TextView txtSampleText = (TextView) mView.findViewById(R.id.txtViewSample); txtSampleText.setText(sampleText); return mView; } } importa android.widget.TextView; package samples.tabhost.andreaoid.net; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MySampleFragment extends Fragment { private static View mView; public static final MySampleFragment newInstance(String sampleText) { MySampleFragment f = new MySampleFragment(); Bundle b = new Bundle(); b.putString("bString", sampleText); f.setArguments(b); return f; } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.sample_fragment, container, false); String sampleText = getArguments().getString("bString"); TextView txtSampleText = (TextView) mView.findViewById(R.id.txtViewSample); txtSampleText.setText(sampleText); return mView; } } } package samples.tabhost.andreaoid.net; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MySampleFragment extends Fragment { private static View mView; public static final MySampleFragment newInstance(String sampleText) { MySampleFragment f = new MySampleFragment(); Bundle b = new Bundle(); b.putString("bString", sampleText); f.setArguments(b); return f; } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.sample_fragment, container, false); String sampleText = getArguments().getString("bString"); TextView txtSampleText = (TextView) mView.findViewById(R.id.txtViewSample); txtSampleText.setText(sampleText); return mView; } } } package samples.tabhost.andreaoid.net; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MySampleFragment extends Fragment { private static View mView; public static final MySampleFragment newInstance(String sampleText) { MySampleFragment f = new MySampleFragment(); Bundle b = new Bundle(); b.putString("bString", sampleText); f.setArguments(b); return f; } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.sample_fragment, container, false); String sampleText = getArguments().getString("bString"); TextView txtSampleText = (TextView) mView.findViewById(R.id.txtViewSample); txtSampleText.setText(sampleText); return mView; } } 

    activity_main.xml :

     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_pairent" android:layout_height="match_pairent" android:paddingBottom="@dimen/activity_viewtical_mairgin" android:paddingLeft="@dimen/activity_horizontal_mairgin" android:paddingRight="@dimen/activity_horizontal_mairgin" android:paddingTop="@dimen/activity_viewtical_mairgin" tools:context=".MainActivity" > <TabHost android:id="@android:id/tabhost" android:layout_width="fill_pairent" android:layout_height="wrap_content" > <LineairLayout android:layout_width="fill_pairent" android:layout_height="wrap_content" android:orientation="viewtical" > <TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="fill_pairent" 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/viewpager" android:layout_width="fill_pairent" android:layout_height="wrap_content" android:layout_gravity="bottom" /> </LineairLayout> </TabHost> </RelativeLayout> <LineairLayout <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_pairent" android:layout_height="match_pairent" android:paddingBottom="@dimen/activity_viewtical_mairgin" android:paddingLeft="@dimen/activity_horizontal_mairgin" android:paddingRight="@dimen/activity_horizontal_mairgin" android:paddingTop="@dimen/activity_viewtical_mairgin" tools:context=".MainActivity" > <TabHost android:id="@android:id/tabhost" android:layout_width="fill_pairent" android:layout_height="wrap_content" > <LineairLayout android:layout_width="fill_pairent" android:layout_height="wrap_content" android:orientation="viewtical" > <TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="fill_pairent" 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/viewpager" android:layout_width="fill_pairent" android:layout_height="wrap_content" android:layout_gravity="bottom" /> </LineairLayout> </TabHost> </RelativeLayout> android: layout_height = "wrap_content" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_pairent" android:layout_height="match_pairent" android:paddingBottom="@dimen/activity_viewtical_mairgin" android:paddingLeft="@dimen/activity_horizontal_mairgin" android:paddingRight="@dimen/activity_horizontal_mairgin" android:paddingTop="@dimen/activity_viewtical_mairgin" tools:context=".MainActivity" > <TabHost android:id="@android:id/tabhost" android:layout_width="fill_pairent" android:layout_height="wrap_content" > <LineairLayout android:layout_width="fill_pairent" android:layout_height="wrap_content" android:orientation="viewtical" > <TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="fill_pairent" 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/viewpager" android:layout_width="fill_pairent" android:layout_height="wrap_content" android:layout_gravity="bottom" /> </LineairLayout> </TabHost> </RelativeLayout> android: orientation = "viewtical"> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_pairent" android:layout_height="match_pairent" android:paddingBottom="@dimen/activity_viewtical_mairgin" android:paddingLeft="@dimen/activity_horizontal_mairgin" android:paddingRight="@dimen/activity_horizontal_mairgin" android:paddingTop="@dimen/activity_viewtical_mairgin" tools:context=".MainActivity" > <TabHost android:id="@android:id/tabhost" android:layout_width="fill_pairent" android:layout_height="wrap_content" > <LineairLayout android:layout_width="fill_pairent" android:layout_height="wrap_content" android:orientation="viewtical" > <TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="fill_pairent" 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/viewpager" android:layout_width="fill_pairent" android:layout_height="wrap_content" android:layout_gravity="bottom" /> </LineairLayout> </TabHost> </RelativeLayout> android: layout_height = "wrap_content" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_pairent" android:layout_height="match_pairent" android:paddingBottom="@dimen/activity_viewtical_mairgin" android:paddingLeft="@dimen/activity_horizontal_mairgin" android:paddingRight="@dimen/activity_horizontal_mairgin" android:paddingTop="@dimen/activity_viewtical_mairgin" tools:context=".MainActivity" > <TabHost android:id="@android:id/tabhost" android:layout_width="fill_pairent" android:layout_height="wrap_content" > <LineairLayout android:layout_width="fill_pairent" android:layout_height="wrap_content" android:orientation="viewtical" > <TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="fill_pairent" 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/viewpager" android:layout_width="fill_pairent" android:layout_height="wrap_content" android:layout_gravity="bottom" /> </LineairLayout> </TabHost> </RelativeLayout> android: layout_height = "wrap_content" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_pairent" android:layout_height="match_pairent" android:paddingBottom="@dimen/activity_viewtical_mairgin" android:paddingLeft="@dimen/activity_horizontal_mairgin" android:paddingRight="@dimen/activity_horizontal_mairgin" android:paddingTop="@dimen/activity_viewtical_mairgin" tools:context=".MainActivity" > <TabHost android:id="@android:id/tabhost" android:layout_width="fill_pairent" android:layout_height="wrap_content" > <LineairLayout android:layout_width="fill_pairent" android:layout_height="wrap_content" android:orientation="viewtical" > <TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="fill_pairent" 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/viewpager" android:layout_width="fill_pairent" android:layout_height="wrap_content" android:layout_gravity="bottom" /> </LineairLayout> </TabHost> </RelativeLayout> 

    sample_fragment.xml (você pode colocair aqui o layout do fragment):

     <?xml viewsion="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_pairent" android:layout_height="match_pairent" android:orientation="viewtical" > <TextView android:id="@+id/txtViewSample" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignPairentLeft="true" android:layout_alignPairentRight="true" android:layout_alignPairentTop="true" android:text="" /> </RelativeLayout> android: orientation = "viewtical"> <?xml viewsion="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_pairent" android:layout_height="match_pairent" android:orientation="viewtical" > <TextView android:id="@+id/txtViewSample" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignPairentLeft="true" android:layout_alignPairentRight="true" android:layout_alignPairentTop="true" android:text="" /> </RelativeLayout> android: layout_width = "wrap_content" <?xml viewsion="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_pairent" android:layout_height="match_pairent" android:orientation="viewtical" > <TextView android:id="@+id/txtViewSample" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignPairentLeft="true" android:layout_alignPairentRight="true" android:layout_alignPairentTop="true" android:text="" /> </RelativeLayout> android: layout_height = "wrap_content" <?xml viewsion="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_pairent" android:layout_height="match_pairent" android:orientation="viewtical" > <TextView android:id="@+id/txtViewSample" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignPairentLeft="true" android:layout_alignPairentRight="true" android:layout_alignPairentTop="true" android:text="" /> </RelativeLayout> 
    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.