2014-11-03 2 views
1

Я хочу изменить вкладку, прокручивая экран. Я создаю вкладки, используя фрагмент tabhost, но когда я реализую функцию прокрутки в моем проекте, он не открывает вложенный фрагмент на каждой вкладке, потому что я открытие вложенного дочернего фрагмента внутри каждой вкладки.Как добавить жестов на фрагменте 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 

     } 


    } 

Этот фрагмент Контейнерный класс

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


} 
+0

Вы когда-нибудь получали ответ для этого, который использует фрагмент фрагмента? – MidasLefko

ответ

1

Вы должны использовать ViewPager. Подробнее на Android Developer website. На Android Arsenal вы можете найти множество настраиваемых пейджеров. Это текущий стандарт, поэтому вы должны использовать его по сравнению с TabHost.

+0

, когда я использую просмотр пейджера, я использую функцию прокрутки, но вкладки вернутся, а вложенный фрагмент внутри вкладки не получается. – user3679400

+0

. Пожалуйста, помогите. Я хочу, чтобы функция прокрутки и вложенный фрагмент открывались на узле вкладки фрагмента вместо вкладок панели действий. – user3679400

0

вы можете посмотреть на его демо в Eclips пойти Файл-> Другие-> Android деятельность-> вкладками деятельности

или узнать вид Fliper с веб-сайта для разработчиков Android

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 
 
\t \t ActionBar.TabListener { 
 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 
\t \t @Override 
 
\t \t public Fragment getItem(int position) { 
 
\t \t \t 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; 
 
     } 
 
\t \t } 
 

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

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

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

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

 
\t \t public PlaceholderFragment() { 
 
\t \t } 
 

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

 
} 
 

 
                   
 
                   
 
                  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> 
 

 
     

Используйте этот метод в своей деятельности для всех фрагментов trancation

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

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

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

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

 
\t \t } 
 

 
\t }

и использовать его, как это всякий раз, когда вам нужно идти для вложенного фрагмента из одного fragmnet

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

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

в приведенном выше предположим, я нахожусь в детали фрагмента и от здесь я хочу пойти в cartfragment , затем получить экземпляр activitiy и бросить его, как указано выше

+0

, когда я используйте плейер представления, он принимает функцию прокрутки, но вкладки вернутся, а вложенный фрагмент внутри вкладки не открывается. – user3679400

+0

напишите свой код здесь –

+0

Я отредактировал свой вопрос .. – user3679400

Смежные вопросы