如何在片段TAbHost上添加滑动手势

时间:2014-11-03 13:04:12

标签: android swipe-gesture fragment-tab-host tabcontainer

我想通过在屏幕上滑动来更改选项卡我正在使用片段tabhost创建选项卡但是当我在我的项目中实现滑动功能时,它不会在每个选项卡中打开嵌套片段意味着我在每个选项卡中打开嵌套子片段。

请告诉我这对我很重要。

这是我的代码。

这是我的主要活动。

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

        }


    } 

此Container片段类

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;
        }

    }

为每个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文件

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;
    }


}

2 个答案:

答案 0 :(得分:1)

您必须使用ViewPager。阅读Android Developer website的更多内容。您可以在Android Arsenal上找到大量自定义视图寻呼机。这是当前的标准,因此您应该使用TabHost

答案 1 :(得分:0)

你可以看看它在eclips中的演示 file-&gt; other-&gt; android Activity-&gt; tabbed activity

或从Android开发者网站了解视图Fliper

&#13;
&#13;
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>

          
&#13;
&#13;
&#13;

在您的活动中使用此方法进行所有片段转换

&#13;
&#13;
// 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();

		}

	}
&#13;
&#13;
&#13;

并在需要从一个fragmnet

获取嵌套片段时使用它

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

				((HomeActivity) DetailsFragment.this.getActivity())
						.replaceFragment(cartfragment);
&#13;
&#13;
&#13;

在上面假设我在细节片段,从这里我想去cartfragment 然后得到活动实例并像上面那样投射它