1

I want to change tab by swiping on the screen i am creating tabs using fragment tabhost but when i implement swiping feature in my project it doesn't open nested fragment in each tab means i am opening nested child fragment inside each tab.

Please tell me its very important for me.

here is my code.

this my Main activity.

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

    public class Home extends FragmentActivity implements OnTabChangeListener,OnPageChangeListener {

        private static final String TAB_1_TAG = "tab_1";
        private static final String TAB_2_TAG = "tab_2";
        private static final String TAB_3_TAG = "tab_3";
        private static final String TAB_4_TAG = "tab_4";
        private static final String TAB_5_TAG = "tab_5";
        private FragmentTabHost mTabHost;
//        ViewPager viewPager;
//        TabsPagerAdapter mAdapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);

           viewPager =(ViewPager)findViewById(R.id.viewpager);
            initView();
            mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
            viewPager.setAdapter(mAdapter);
            viewPager.setOnPageChangeListener(Home.this);

        }

        private void initView() {
            mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
            mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

           // mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk", getResources().getDrawable(R.drawable.ic_launcher)), TalkContainerFragment.class, null);
            mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk"), TalkContainerFragment.class, null);
            mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("Map"), Map_fragment.class, null);
//            mTabHost.addTab(mTabHost.newTabSpec(TAB_3_TAG).setIndicator("Go"), GoContainerFragment.class, null);
//            mTabHost.addTab(mTabHost.newTabSpec(TAB_4_TAG).setIndicator("Watch"), WatchContainerFragment.class, null);
//            mTabHost.addTab(mTabHost.newTabSpec(TAB_5_TAG).setIndicator("More"), MoreContainerFragment.class, null);

            /* Increase tab height programatically 
             * tabs.getTabWidget().getChildAt(1).getLayoutParams().height = 150; 
             */

            for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
                final TextView tv = (TextView) mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
                if (tv == null)
                continue;
                else
                tv.setTextSize(10);

            }

        }

        @Override
        public void onBackPressed() {
            boolean isPopFragment = false;
            String currentTabTag = mTabHost.getCurrentTabTag();
            if (currentTabTag.equals(TAB_1_TAG)) {
                isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
            } else if (currentTabTag.equals(TAB_2_TAG)) {
                isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
            } else if (currentTabTag.equals(TAB_3_TAG)) {
                isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_3_TAG)).popFragment();
            } else if (currentTabTag.equals(TAB_4_TAG)) {
                isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_4_TAG)).popFragment();
            } else if (currentTabTag.equals(TAB_5_TAG)) {
                isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_5_TAG)).popFragment();
            }
            if (!isPopFragment) {
                finish();
            }
        }

        @Override
        public void onTabChanged(String tabId) {
            // TODO Auto-generated method stub
            int pos = this.mTabHost.getCurrentTab();
            this.viewPager.setCurrentItem(pos);
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
            int pos = this.viewPager.getCurrentItem();
            this.mTabHost.setCurrentTab(pos);
        }

        @Override
        public void onPageSelected(int arg0) {
            // TODO Auto-generated method stub

        }


    } 

This Container fragment class

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;

    public class BaseContainerFragment extends Fragment {

        public void replaceFragment(Fragment fragment, boolean addToBackStack) {
            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
            if (addToBackStack) {
                transaction.addToBackStack(null);
            }
            transaction.replace(R.id.container_framelayout, fragment);
            transaction.commit();
            getChildFragmentManager().executePendingTransactions();
        }

        public boolean popFragment() {
            Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
            boolean isPop = false;
            if (getChildFragmentManager().getBackStackEntryCount() > 0) {
                isPop = true;
                getChildFragmentManager().popBackStack();
            }
            return isPop;
        }

    }

Created Container for each TAb

  import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

        public class TalkContainerFragment extends BaseContainerFragment {

            private boolean mIsViewInited;

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                Log.e("test", "tab 1 oncreateview");
                return inflater.inflate(R.layout.container_fragment, null);
            }

            @Override
            public void onActivityCreated(Bundle savedInstanceState) {
                super.onActivityCreated(savedInstanceState);
                Log.e("test", "tab 1 container on activity created");
                if (!mIsViewInited) {
                    mIsViewInited = true;
                    initView();
                }
            }

TAlk.java file

import java.util.HashSet;
import java.util.Set;

import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class Talk extends Fragment {

    /** Define global variables over here */
    //private ProgressDialog pDialog;
//    StaticApiList sal;
//    TalkModelAll tma;
    JSONObject myJasonObject = null;
    private ListView lv;
//    private ArrayList<TalkModelAll> m_ArrayList = null;
    //ArrayList<String> stringArrayList = new ArrayList<String>();
//    TalkArrayAdapter taa;
    Set<String> uniqueValues = new HashSet<String>();
    TextView rowTextView = null;
    boolean vivek = false;

    int postid;
    String title;
    String thumsrc;
    String largeimg;
    String excert;
    String description;
    String cat;
    String myUrl;
    String jsonString;
    int mCurCheckPosition;
    String check_state = null;
    String ccc;
    LinearLayout myLinearLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.talk, null);

        Button btn = (Button) rootView.findViewById(R.id.your_btn_id);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //Here TalkDetail is name of class that needs to open
                TalkDetail talkfragment = new TalkDetail();
                // if U need to pass some data 
                Bundle bundle = new Bundle();
//
//                bundle.putString("title", m_ArrayList.get(arg2).title);
//                bundle.putString("largeimg", m_ArrayList.get(arg2).largeimg);
//                bundle.putString("excert", m_ArrayList.get(arg2).excert);
//                bundle.putString("description", m_ArrayList.get(arg2).description);
//                bundle.putString("cat", m_ArrayList.get(arg2).cat);
//                //bundle.putInt("postid", m_ArrayList.get(arg2).postid);

                talkfragment.setArguments(bundle);
                ((BaseContainerFragment)getParentFragment()).replaceFragment(talkfragment, true);
            }
        });

        return rootView;
    }
}

Talkddetail.class

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

public class TalkDetail extends android.support.v4.app.Fragment {

    /* (non-Javadoc)
     * @see android.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view=LayoutInflater.from(getActivity()).inflate(R.layout.activity_talk_detail, null);
        return view;
    }


}
user3679400
  • 87
  • 1
  • 9

2 Answers2

1

You have to use a ViewPager. Read more at Android Developer website. You can find a lot of custom view pagers on Android Arsenal. This is the current standard, so you should use this over TabHost.

Tamás Cseh
  • 3,050
  • 1
  • 20
  • 30
  • when i use view pager i adopt the swiping feature but tabs come to top and nested fragment inside tab doesn't get opned – user3679400 Nov 03 '14 at 13:27
  • Please help I want swiping feature and nested fragment to open on fragment tab host instead of action bar tabs – user3679400 Nov 07 '14 at 09:39
0

you can have a look at its demo in eclips go to file->other->android Activity->tabbed activity

or learn the view Fliper from android developer website

package com.example.mystack;

import java.util.Locale;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity implements
  ActionBar.TabListener {

 /**
  * The {@link android.support.v4.view.PagerAdapter} that will provide
  * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
  * derivative, which will keep every loaded fragment in memory. If this
  * becomes too memory intensive, it may be best to switch to a
  * {@link android.support.v4.app.FragmentStatePagerAdapter}.
  */
 SectionsPagerAdapter mSectionsPagerAdapter;

 /**
  * The {@link ViewPager} that will host the section contents.
  */
 ViewPager mViewPager;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // Set up the action bar.
  final ActionBar actionBar = getSupportActionBar();
  actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

  // Create the adapter that will return a fragment for each of the three
  // primary sections of the activity.
  mSectionsPagerAdapter = new SectionsPagerAdapter(
    getSupportFragmentManager());

  // Set up the ViewPager with the sections adapter.
  mViewPager = (ViewPager) findViewById(R.id.pager);
  mViewPager.setAdapter(mSectionsPagerAdapter);

  // When swiping between different sections, select the corresponding
  // tab. We can also use ActionBar.Tab#select() to do this if we have
  // a reference to the Tab.
  mViewPager
    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
     @Override
     public void onPageSelected(int position) {
      actionBar.setSelectedNavigationItem(position);
     }
    });

  // For each of the sections in the app, add a tab to the action bar.
  for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
   // Create a tab with text corresponding to the page title defined by
   // the adapter. Also specify this Activity object, which implements
   // the TabListener interface, as the callback (listener) for when
   // this tab is selected.
   actionBar.addTab(actionBar.newTab()
     .setText(mSectionsPagerAdapter.getPageTitle(i))
     .setTabListener(this));
  }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  // Handle action bar item clicks here. The action bar will
  // automatically handle clicks on the Home/Up button, so long
  // as you specify a parent activity in AndroidManifest.xml.
  int id = item.getItemId();
  if (id == R.id.action_settings) {
   return true;
  }
  return super.onOptionsItemSelected(item);
 }

 @Override
 public void onTabSelected(ActionBar.Tab tab,
   FragmentTransaction fragmentTransaction) {
  // When the given tab is selected, switch to the corresponding page in
  // the ViewPager.
  mViewPager.setCurrentItem(tab.getPosition());
 }

 @Override
 public void onTabUnselected(ActionBar.Tab tab,
   FragmentTransaction fragmentTransaction) {
 }

 @Override
 public void onTabReselected(ActionBar.Tab tab,
   FragmentTransaction fragmentTransaction) {
 }

 /**
  * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
  * one of the sections/tabs/pages.
  */
 public class SectionsPagerAdapter extends FragmentPagerAdapter {

  public SectionsPagerAdapter(FragmentManager fm) {
   super(fm);
  }

  @Override
  public Fragment getItem(int position) {
   switch (position) {
        case 0: // Fragment # 0 - This will show FirstFragment
            return new TalkContainerFragment(0, "Talk");
        case 1: // Fragment # 0 - This will show FirstFragment different title
            return new Map_fragment(1, "map");
       //Rest of them add here
        default:
            return null;
        }
  }

  @Override
  public int getCount() {
   // Show 3 total pages.
   return 3;
  }

  @Override
  public CharSequence getPageTitle(int position) {
   Locale l = Locale.getDefault();
   switch (position) {
   case 0:
    return getString(R.string.title_section1).toUpperCase(l);
   case 1:
    return getString(R.string.title_section2).toUpperCase(l);
   case 2:
    return getString(R.string.title_section3).toUpperCase(l);
   }
   return null;
  }
 }

 /**
  * A placeholder fragment containing a simple view.
  */
 public static class PlaceholderFragment extends Fragment {
  /**
   * The fragment argument representing the section number for this
   * fragment.
   */
  private static final String ARG_SECTION_NUMBER = "section_number";

  /**
   * Returns a new instance of this fragment for the given section number.
   */
  public static PlaceholderFragment newInstance(int sectionNumber) {
   PlaceholderFragment fragment = new PlaceholderFragment();
   Bundle args = new Bundle();
   args.putInt(ARG_SECTION_NUMBER, sectionNumber);
   fragment.setArguments(args);
   return fragment;
  }

  public PlaceholderFragment() {
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
   View rootView = inflater.inflate(R.layout.fragment_main, container,
     false);
   return rootView;
  }
 }

}

                                                             
                                                             
                                                             and xml is
                                                             
                                                             <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mystack.MainActivity" />



<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="com.example.mystack.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

          

Use this method in your activity for all fragment trancation

// For the Fragment Replace And AddtobackStack
 void replaceFragment(Fragment fragment) {
  String backStateName = fragment.getClass().getName();
  String fragmentTag = backStateName;

  FragmentManager manager = this.getSupportFragmentManager();
  boolean fragmentPopped = manager
    .popBackStackImmediate(backStateName, 0);

  if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) {
   // fragment not in back stack, create it.
   FragmentTransaction ft = manager.beginTransaction();
   ft.replace(R.id.container, fragment, fragmentTag);
   ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

   ft.addToBackStack(backStateName);
   ft.commit();

  }

 }

and use it like this whenever you need to go for nested fragment from one fragmnet

if (DetailsFragment.this.getActivity() != null
     && DetailsFragment.this.getActivity() instanceof HomeActivity)

    ((HomeActivity) DetailsFragment.this.getActivity())
      .replaceFragment(cartfragment);

in the above suppose i am in details fragment and from here i want to go to cartfragment then get the activitiy instance and cast it like the above

amit kumar
  • 291
  • 1
  • 6