Creating an Android app using TabHost and multiple fragments - android

I have been trying to create a basic Android app that contains tabs, which when clicked will load a new fragment - each fragment being a separate xml file. I would like to use TabHost and not the Activity Bar tabs. I have been looking through many tutorials on the web and posts here on stackoverflow, but to no avail. Most questions and tutorials are discussing either fragments OR tabs, but not both subjects. Thank you in advance for the suggestions.
I would like to try a very basic app that contains:
one fragment to input a number - xml file_1 (1st tab)
one fragment to display the number in a TextView - xml file_2 (2nd tab)

try like this
your xml file
<?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" >
<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="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<FrameLayout
android:id="#+id/tab_1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dip"
android:layout_marginRight="0dip"
android:layout_weight="0" />
</LinearLayout>
</TabHost>
</LinearLayout>
In your activity onCreate
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(0);
setupTabs();
setupTabs() method
private void setupTabs() {
mTabHost.setup();
setupTab(new TextView(this), "Tab1");
setupTab(new TextView(this), "Tab2");
setupTab(new TextView(this), "Tab3");
mTabHost.getTabWidget().setDividerDrawable(R.drawable.empty);//not necessery
}
setupTab() method //setup a single tab
private void setupTab(final View view, final String tag) {
View tabview = createTabView(mTabHost.getContext(), tag);
TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(new TabContentFactory() {
public View createTabContent(String tag) {
return view;
}
});
mTabHost.addTab(setContent);
}
createTabView method
private static View createTabView(final Context context, final String text) {
int resouceId = R.layout.tabs_bg;
if(text.equals("Tab1")) {
resouceId = R.layout.tab_1_layout;
} else if(text.equals("Tab2")) {
resouceId = R.layout.tab_2_layout;
}
View view = LayoutInflater.from(context).inflate(resouceId, null);
return view;
}
onTabChanged method
#Override
public void onTabChanged(String tabId) {
Log.d("TAB_CHANGE","onTabChanged(): tabId=" + tabId);
updateTab(tabId, R.id.tab_1,new YourFragment());
}
public void updateTab(String tabId, int placeholder,Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(placeholder,fragment, tabId)
.commit();
}

First off, thanks to deniz for getting me close enough to the right solution I could eke out a working project. Now, this should be closer to functional. I changed names to be generic, but hopefully everything will work as intended and be enough to help you understand what's happening.
TabHostActivity (your main Activity):
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
public class TabHostActivity extends FragmentActivity implements TabHost.OnTabChangeListener
{
private static final String TAG = "TabHostActivity";
private TabHost tabHost;
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabhost);
tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setOnTabChangedListener(this);
tabHost.setCurrentTab(0);
setupTabs();
}
private void setupTabs()
{
tabHost.setup();
setupTab(new TextView(this), "tab1");
setupTab(new TextView(this), "tab2");
setupTab(new TextView(this), "tab3");
setupTab(new TextView(this), "tab4");
}
private void setupTab(final View view, final String tag)
{
View tabview = createTabView(tabHost.getContext(), tag);
TabHost.TabSpec setContent = tabHost.newTabSpec(tag)
.setIndicator(tabview)
.setContent(new TabHost.TabContentFactory()
{
public View createTabContent(String tag)
{
return view;
}
});
tabHost.addTab(setContent);
}
/**
* Return the view for the individual tabs, the tab view being set is identified by tabId.
*
* #param context
* #param tabId
* #return
*/
private static View createTabView(final Context context, final String tabId)
{
int resourceId;
if (tabId.equals("tab1"))
{
resourceId = R.layout.tab1;
}
else if (tabId.equals("tab2"))
{
resourceId = R.layout.tab2;
}
else if (tabId.equals("tab3"))
{
resourceId = R.layout.tab3;
}
else
{
resourceId = R.layout.tab4;
}
return LayoutInflater.from(context).inflate(resourceId, null);
}
#Override
public void onTabChanged(String tabId)
{
Log.d(TAG, "onTabChanged(): tabId=" + tabId);
if (tabId.equalsIgnoreCase("tab1"))
{
updateTab(android.R.id.tabcontent, new tab1(), tabId);
}
else if (tabId.equalsIgnoreCase("tab2"))
{
updateTab(android.R.id.tabcontent, new tab2(), tabId);
}
else if (tabId.equalsIgnoreCase("tab3"))
{
updateTab(android.R.id.tabcontent, new tab3(), tabId);
}
else
{
updateTab(android.R.id.tabcontent, new tab4(), tabId);
}
}
public void updateTab(int placeholder, Fragment fragment, String tabId)
{
getSupportFragmentManager().beginTransaction()
.replace(placeholder, fragment, tabId)
.commit();
}
}
activity_tabhost.xml:
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<FrameLayout
android:id="#+id/tab_1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+id/tab_2"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+id/tab_3"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+id/tab_4"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout >
</TabHost >
tab1.xml, tab2.xml, tab3.xml, tab4.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
tab1.java, tab2.java, tab3.java, tab4.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class tab1 extends Fragment
{
private static final String TAG = "tab1";
#Override
public void onActivityCreated(final Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "onActivityCreated");
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
Log.i(TAG, "onCreateView");
return inflater.inflate(R.layout.tab1, container, false);
}
}
AndroidManifest.xml:
<activity android:name="<YOUR_PACKAGE_NAME>.TabHostActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This was done using v19 of the API as target, and with a minimum of v10 using the android.support.v4.app library.
So again, thank you deniz for getting me to this point, I had spent 10 hours trying things and everything I found was out of date. Hopefully this can help other people who are in my ex-state of limbo. You should now have a working state and can see where you can design the tabs as well as where you put the contents of the Fragments.
PS - yes, in my generalization pass it did result in the xml content and the tabs being called "tab1.whatever", hopefully this isn't too confusing, which is which can be deduced with a little context.

Related

Android fragment tab host + viewpager swipe?

I currently have a fragment tab host, made by this tutorial
http://maxalley.wordpress.com/2013/05/18/android-creating-a-tab-layout-with-fragmenttabhost-and-fragments/
The only difference is that I'm using this inside a fragment.
So I have a fragment with the tabs, each tab has another fragment..
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
The fragment class
public class AddServiceFragment extends Fragment {
public AddServiceFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add_service, container, false);
FragmentTabHost mTabHost = (FragmentTabHost) view.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), android.R.id.tabcontent);
String[] tabs = new String[]{"text1", "text2"};
mTabHost.addTab(
mTabHost.newTabSpec("tab1").setIndicator(tabs[0], null),
MedicalHistoryFragment.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab2").setIndicator(tabs[1], null),
MedicalHistoryFragment.class, null);
return view;
}
This works, I can see my tabs.
Now I want to implement a viewpager, in order to be able to swipe left or right.
I've read this from the android developer page
http://developer.android.com/training/animation/screen-slide.html
But I can't figure out, where should I put my viewpager?
I want my fragment to be independent of my activity...
TabHost doesn't provide ViewPager support.
Also, I suggest you to not use TabHost – this is old style.
Use PagerTabStrip
Look this Gist.
UPD:
I add some code, for case, if this Gist be deleted;
MainActivity.java
package ch.pboos.android.sample.viewpager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new SampleFragmentPagerAdapter());
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 5;
public SampleFragmentPagerAdapter() {
super(getSupportFragmentManager());
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
return PageFragment.create(position + 1);
}
}
public static class PageFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static PageFragment create(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page, container, false);
TextView textView = (TextView) view;
textView.setText("Fragment #" + mPage);
return view;
}
}
}
activity_main.xml (without PagerTabStrip)
<?xml version="1.0" encoding="utf-8"?>
<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" >
</android.support.v4.view.ViewPager>
activity_main_2.xml (with PagerTabStrip)
<?xml version="1.0" encoding="utf-8"?>
<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" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#000"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
fragment_page.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" />
getPageTitle
public CharSequence getPageTitle(int position) {
return "Page " + (position + 1);
}
UPD 2
With Fragment:
public class MainFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main_2, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new SampleFragmentPagerAdapter());
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 5;
public SampleFragmentPagerAdapter() {
super(getSupportFragmentManager());
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
return PageFragment.create(position + 1);
}
}
public static class PageFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static PageFragment create(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page, container, false);
TextView textView = (TextView) view;
textView.setText("Fragment #" + mPage);
return view;
}
}
}
Hope it helps
use the following solution i have put the view page like below.. and my work done..
<RelativeLayout 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"
tools:context=".MainActivity" >
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<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="wrap_content"
android:layout_weight="0"
android:orientation="horizontal" />
<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="wrap_content"
android:layout_gravity="bottom"
android:overScrollMode="never" />
</LinearLayout>
</TabHost>
You can implement the viewpager as a library.
First thing you need to import viewpager project to the eclipse workspace.
[ I think you are modifying the project :Tabhost example]
so right click your Tabhost example project thn build path -> configure build path..
thn click Android ...when you click android you can see 2 section Project build Target & Library.So in Library you can add the viewpager Library.
Inorder to include viewpager library to the project ,you should import the library
"Existing Project” to your current one.
Step 1:-Download source code from GitHub.(https://github.com/JakeWharton/Android-ViewPagerIndicator)
Step2 :-In your Android Studio Project:
File -> Project Structure -> add (+ symbol) -> Import Existing Project. Import just the folder called ”library”, not the entire project (leave the import options as Android Studio suggests).
step 3:-If the "compileSdkVersion" specified in your build.gradle doesn’t match with the one specified in the Android-ViewPagerIndicator project, change the second one.
The same apply with any other property, such as "minSdkVersion" or even the current support library.
Step 4:-Add Android-ViewPagerIndicator project as a dependency to your build.gradle module:
dependencies {
compile project(':library')
}
Step 5:- Sync project with gradle files.

Tutorial to implement the use of TabHost in Android 2.2 + ViewPager and Fragments

A short tutorial for people like me who had some trouble finding a way to implement TabHost and ViewPager, including page swiping with fingers and tab click to change pages. The shown solution is compatible with Android versions 2.2+.
It includes Tabs initialization, ViewPager connected with Tabs and Page Scrolling management.
Its main peculiarity is the optimization for earlier versions of Android (Android 2.2 (Froyo), API version 8) and the simple implementation for different purposes.
The tutorial includes 4 classes and 2 layouts. It has been tested with an Android phone 2.2, and you can just copy & paste to try it.
MainActivity.java (the main activity):
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;
#Override
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);
}
#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) {
}
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 (fragment manager):
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;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
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;
}
}
MySampleFragment.java (the single fragment - included for demonstration purposes):
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;
}
#Override
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_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</LinearLayout>
</TabHost>
</RelativeLayout>
sample_fragment.xml (you can put here your fragment layout):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtViewSample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="" />
</RelativeLayout>

TabHost with Fragments and FragmentActivity

I'm working on an Android App and I want to use 3 tabs for navigation using Fragments for each tab, but I don't know how to create the structure for doing it.
I want to add each fragment separately because each one is different, but I don't know where to add them in FragmentActivity.
I have these files.
tabs_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent">
<TabHost android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<FrameLayout
android:id="#+id/tabRateAPet"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<FrameLayout
android:id="#+id/tabViewMyRates"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<FrameLayout
android:id="#+id/tabViewGlobalRates"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
TabsMain.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
public class MainTabsActivity extends FragmentActivity {
public static final String RATE_A_PET = "Rate a Pet";
public static final String MY_RATES = "My Rates";
public static final String GLOBAL_RATES = "Global Rates";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs_layout);
}
}
Tabs.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
public class Tabs extends Fragment implements OnTabChangeListener {
private static final String TAG = "FragmentTabs";
public static final String RATE_A_PET = "Rate a Pet";
public static final String MY_RATES = "My Rates";
public static final String GLOBAL_RATES = "Global Rates";
private View mRoot;
private TabHost mTabHost;
private int mCurrentTab;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
mRoot = inflater.inflate(R.layout.tabs_layout, null);
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
private void setupTabs() {
mTabHost.setup(); // important!
mTabHost.addTab(newTab(RATE_A_PET, R.string.tabRateAPet, R.id.tabRateAPet));
mTabHost.addTab(newTab(MY_RATES, R.string.tabViewMyRates, R.id.tabViewMyRates));
}
private TabSpec newTab(String tag, int labelId, int tabContentId) {
Log.d(TAG, "buildTab(): tag=" + tag);
View indicator = LayoutInflater.from(getActivity()).inflate(
R.layout.tab,
(ViewGroup) mRoot.findViewById(android.R.id.tabs), false);
((TextView) indicator.findViewById(R.id.text)).setText(labelId);
TabSpec tabSpec = mTabHost.newTabSpec(tag);
tabSpec.setIndicator(indicator);
tabSpec.setContent(tabContentId);
return tabSpec;
}
#Override
public void onTabChanged(String tabId) {
Log.d(TAG, "onTabChanged(): tabId=" + tabId);
if (RATE_A_PET.equals(tabId)) {
updateTab(tabId, R.id.tabRateAPet);
mCurrentTab = 0;
return;
}
if (MY_RATES.equals(tabId)) {
updateTab(tabId, R.id.tabViewMyRates);
mCurrentTab = 1;
return;
}
if (GLOBAL_RATES.equals(tabId)) {
updateTab(tabId, R.id.tabViewGlobalRates);
mCurrentTab = 2;
return;
}
}
private void updateTab(String tabId, int placeholder) {
FragmentManager fm = getFragmentManager();
if (fm.findFragmentByTag(tabId) == null) {
fm.beginTransaction()
.replace(placeholder, new RateMyPetActivity(), tabId)
.commit();
}
}
}
I would suggest creating a separate fragment file for each tab. I recently did this as well, so I have outlined my code below:
Layout Files
activity_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">
<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.app.FragmentTabHost>
tab1_view.xml //add your respective tab layouts using this format (make sure to change string variables)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".DeviceFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab1_fragment_string" />
</LinearLayout>
SRC Files
MainActivity.java //notice that in the .addTab process I only used text. You can also add icons using drawables that you would need to add to your hdpi folder. I also only created three tabs in this example.
package com.example.applicationname;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
public class MainActivity extends FragmentActivity {
// Fragment TabHost as mTabHost
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
Tab1Fragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
Tab2Fragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("Tab3"),
Tab3Fragment.class, null);
}
}
Tab1Fragment.java //once again replicate for desired number of tabs
package com.example.applicationname;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Tab1Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View V = inflater.inflate(R.layout.tab1_view, container, false);
return V;
}
}
Make sure that your R.java and strings.xml files are properly set up, and then your tabs should be up and running.
TabHost doesn't retains Fragment's states. So why using TabHost?
So use ViewPager with TabLayout instead.
Prons of Viewpager over Tabhost:
ViewPager retains Fragments states. Mean Fragment will not again recreated if switched.
Inbuilt swiping feature that gives user smoother experience.
Less CPU consumption, because Tabhost recreates Fragment/Activity again and again when Tab is switched.
See the difference :
Using Tablayout + ViewPager (Supports swipe, retains Fragments states
Using TabHost (Doesn't support swipe, doesn't retain states)
Small Code for Tablayout + ViewPager
// find views by id
ViewPager viewPager = findViewById(R.id.viewpager);
TabLayout tabLayout = findViewById(R.id.tablayout);
// attach tablayout with viewpager
tabLayout.setupWithViewPager(viewPager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// add your fragments
adapter.addFrag(new SampleFragment(), "Tab1");
adapter.addFrag(new SampleFragment(), "Tab2");
adapter.addFrag(new SampleFragment(), "Tab3");
// set adapter on viewpager
viewPager.setAdapter(adapter);
XML layout
<?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">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
Note If you are not using AndroidX yet, you need to change following in layout.
Change com.google.android.material.tabs.TabLayout to android.support.design.widget.TabLayout
Chagne androidx.viewpager.widget.ViewPager to android.support.v4.view.ViewPager
But I'll strongly recommend to migrate to AndroidX, see #this answer to understand why.
And this is common ViewPagerAdapter for all your Viewpager in app.
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFrag(Fragment fragment) {
mFragmentList.add(fragment);
mFragmentTitleList.add("");
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
Important Related Links
Difference between getSupportFragmentManager() and getChildFragmentManager()?
getSupportFragmentManager() versus getFragmentManager() in android 3.0+
Difference between FragmentPagerAdapter and FragmentStatePagerAdapter

Fragment tab content not shown with HoloEverywhere and ActionbarSherlock

Hi I'm making this app with two fragments that you can swipe between. The code compiles and runs without crashing and both tabs are shown and you can swipe between the tabs but the tabs have no content. I think this is a problem with the fragments trying to setcontentview. If you need anymore info just ask :)
my main activity
import java.util.ArrayList;
import org.holoeverywhere.app.Activity;
import org.holoeverywhere.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockActivity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.WindowManager;
public class SwipeTabsMainActivity extends Activity {
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
TextView tabCenter;
TextView tabText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText("Stopwatch"),StopWatchFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Timer"), CountdownFragment.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(Activity 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);
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
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);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}
the Main Activity's xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
my countdown timer fragment
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.internal._View;
import org.holoeverywhere.preference.PreferenceManager;
import org.holoeverywhere.preference.SharedPreferences;
import org.holoeverywhere.widget.Button;
import org.holoeverywhere.widget.TextView;
import org.holoeverywhere.widget.Toast;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import org.holoeverywhere.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.RelativeLayout;
public class CountdownFragment extends Fragment implements
OnChronometerTickListener {
TextView second, hour, minute;
ImageButton hourup, hourdown, minuteup, minutedown, secondup, seconddown;
Button start, stop;
int hourCount, minCount, secCount;
Context c;
Chronometer count;
boolean viberate, running;
Vibrator v;
boolean startstopshow;
SharedPreferences getPrefs;
View fv = getView();
RelativeLayout rl;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initilize(c);
setClicker();
count.start();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
c = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.countdown, container, false);
rl = (RelativeLayout )inflater.inflate(R.layout.countdown, container, false);
return super.onCreateView(inflater, container, savedInstanceState);
}
private void initilize(Context c) {
hourup = (ImageButton) rl.findViewById(R.id.hourup);
minuteup = (ImageButton) rl.findViewById(R.id.minuteup);
secondup = (ImageButton) rl.findViewById(R.id.secondup);
hourdown = (ImageButton) rl.findViewById(R.id.hourdown);
minutedown = (ImageButton) rl.findViewById(R.id.minutedown);
seconddown = (ImageButton) rl.findViewById(R.id.seconddown);
start = (Button) rl.findViewById(R.id.start);
stop = (Button) rl.findViewById(R.id.stop);
second = (TextView) rl.findViewById(R.id.second);
minute = (TextView) rl.findViewById(R.id.minute);
hour = (TextView) rl.findViewById(R.id.hour);
hourCount = 0;
minCount = 0;
secCount = 0;
count = (Chronometer) rl.findViewById(R.id.chronometer1);
v = (Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE);
running = false;
getPrefs = PreferenceManager.getDefaultSharedPreferences(c);
}
#Override
public void onChronometerTick(Chronometer chronometer) {
switch (chronometer.getId()) {
case (R.id.chronometer1):
secCount--;
updateDisplay();
break;
}
}
}
my fragments xml file
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="56dp" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/hourup"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/up" />
<ImageButton
android:id="#+id/minuteup"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/up" />
<ImageButton
android:id="#+id/secondup"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/up" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<org.holoeverywhere.widget.TextView
android:id="#+id/hour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="00 : "
android:textSize="35sp" />
<org.holoeverywhere.widget.TextView
android:id="#+id/minute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="00 : "
android:textSize="35sp" />
<org.holoeverywhere.widget.TextView
android:id="#+id/second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="00"
android:textSize="35sp" />
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/hourdown"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/down" />
<ImageButton
android:id="#+id/minutedown"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/down" />
<ImageButton
android:id="#+id/seconddown"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/down" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_weight="50"
android:gravity="bottom"
android:weightSum="100" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignParentBottom="true" >
<org.holoeverywhere.internal._View
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="1dip"
android:layout_alignParentTop="true"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:background="?dividerVertical" />
<org.holoeverywhere.internal._View
android:id="#+id/ViewColorPickerHelper"
android:layout_width="1dip"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="4dip"
android:layout_marginTop="4dip"
android:background="?dividerVertical" />
<org.holoeverywhere.widget.Button
android:id="#+id/start"
style="#style/Holo.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/view1"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/stop"
android:text="Start" />
<org.holoeverywhere.widget.Button
android:id="#+id/stop"
style="#style/Holo.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/ViewColorPickerHelper"
android:text="Stop" />
</RelativeLayout>
</LinearLayout>
<Chronometer
android:id="#+id/chronometer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Chronometer"
android:textSize="0px"
android:visibility="invisible" />
</RelativeLayout>
I finally found the problem:
You have to replace : super.onCreateView(inflater, container, savedInstanceState); to your countdown view :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.countdown, container, false);
rl = (RelativeLayout )inflater.inflate(R.layout.countdown, container, false);
return v;
}
Here's a screenshot of the result:
i can see that you are using the ActionBarSherlock. try that library : http://viewpagerindicator.com/ . It will help you and it is really easy to customize you tabs and navigation
You can see alot of examples with the app on Google play : https://play.google.com/store/apps/details?id=com.viewpagerindicator.sample&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS52aWV3cGFnZXJpbmRpY2F0b3Iuc2FtcGxlIl0.
Here's an example :
main activity :
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.viewpagerindicator.TabPageIndicator;
public class MainActivity extends SherlockFragmentActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager()));
//Bind the title indicator to the adapter
TabPageIndicator tabIndicator = (TabPageIndicator)findViewById(R.id.titles);
tabIndicator.setViewPager(mViewPager);
mViewPager.setCurrentItem(1);
}
}
FragmentPagerAdapter:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
private Fragment[] fragments;
private static final String[] CONTENT = new String[] { "frag A","frag B", "frag C" };
// Reference : https://bitbucket.org/owentech/abstabsviewpager/downloads
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
this.fragments = new Fragment[] { new FragmentA(),
new FragmentB(),
new FragmentC()};
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
return this.fragments[arg0];
}
public CharSequence getPageTitle(int position) {
return CONTENT[position];
}
#Override
public int getCount() {
return this.fragments.length;
}
}
FragmentX :
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentA extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmenta, container, false);
return v;
}
}
main xml :
<?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">
<com.viewpagerindicator.TabPageIndicator
android:id="#+id/titles"
android:theme="#style/Theme.PageIndicatorDefaults"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
manifest xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.viewpagertest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Sherlock" >
<activity
android:name="com.example.viewpagertest.MainActivity"
android:label="#string/app_name"
android:theme="#style/Theme.PageIndicatorDefaults" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Dynamic tab in Android with dynamic tab content

I want to create a tab dynamically in Android and under each tab I have one listview. So I want the content of the listview to also change dynamically. How can I do this ?
I saw a code on another forum and cleaned it up a little. To do what you need you'll have to change the stuff inside of ts1.setContent and ts2.setContent
Main_screen.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class Main_screen extends Activity{
private ListView ls1;
private ListView ls2;
private TabHost myTabHost;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
myTabHost = (TabHost)this.findViewById(R.id.th_set_menu_tabhost);
myTabHost.setup();
ls1 = new ListView(Main_screen.this);
TabSpec ts1 = myTabHost.newTabSpec("TAB_TAG_1");
ts1.setIndicator("Tab1");
ts1.setContent(new TabHost.TabContentFactory(){
public View createTabContent(String tag)
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main_screen.this,android.R.layout.simple_list_item_1,new String[]{"item1","item2","item3"});
ls1.setAdapter(adapter);
return ls1;
}
});
myTabHost.addTab(ts1);
ls2 = new ListView(Main_screen.this);
TabSpec ts2 = myTabHost.newTabSpec("TAB_TAG_2");
ts2.setIndicator("Tab2");
ts2.setContent(new TabHost.TabContentFactory(){
public View createTabContent(String tag)
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main_screen.this,android.R.layout.simple_list_item_1,new String[]{"item4","item5","item6"});
ls2.setAdapter(adapter);
return ls2;
}
});
myTabHost.addTab(ts2);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/th_set_menu_tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="64dip" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="75dip">
<ListView
android:id = "#+id/danhsach"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
</TabHost>
for(int i=0; i<5; i++ )
{
final TabSpec x=tabHost2.newTabSpec("x");
View row = inflater.inflate(R.layout.indicator1,null);
final TextView indicator1 =(TextView) row.findViewById(R.id.textView_indicator1);
indicator1.setText(indicator_list[i]);
// indicator1.setShadowLayer(1, 0, 1, 0xFF013201);
x.setIndicator(row);
x.setContent(new TabContentFactory() {
public View createTabContent(String arg) {
return gallery2;
}
});
tabHost2.addTab(x);
}
you can do like this.

Categories

Resources