选项卡执行android中下一个片段中存在的代码

时间:2016-02-24 05:39:54

标签: android android-fragments tabs fragmentpageradapter

我正在尝试使用Tabs和4 ViewPager进行滑动来实施Fragments。当我滑动选项卡时,每个选项卡上的相应xml layouts碎片都会正确显示,但片段的代码未正确执行。 例如 - 以下选项卡中包含相应的片段。

TAB0-ButtonFragment

public class ButtonFragment extends Fragment {

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

    View rootView = inflater.inflate(R.layout.fragment_button, container, false);
    Log.i("inside", "button fragment");
    return rootView;
}

TAB1-ImageFragment

public class ImageFragment extends Fragment {

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

    View rootView = inflater.inflate(R.layout.fragment_image, container, false);
    Log.i("inside", "image fragment");
    return rootView;
}

TAB2-TextFragment

    public class TextFragment extends Fragment {

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

    View rootView = inflater.inflate(R.layout.fragment_text, container, false);
    Log.i("inside", "text fragment");
    return rootView;
}

TAB3试验     公共类测试扩展片段{

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

    View rootView = inflater.inflate(R.layout.temp, container, false);
    Log.i("inside", "tessssssssst fragment");
    return rootView;
}

显示选项卡时 我同时获得了tab0和tab1的日志消息。然后在滑动并转到tab1后,我得到tab2的日志消息。在刷到tab2后,我收到选项卡3的日志消息,当到达选项卡3时,没有显示日志消息。任何人都可以告诉我如何执行相应选项卡的相应代码?我剩下的代码如下:

public class TabsPagerAdapter extends FragmentPagerAdapter { //Update - code formatting

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

@Override
public Fragment getItem( int index) {
    Log.i("index", "" + index);
    switch (index) {
    case 0:
        // Top Rated fragment activity
        return new ButtonFragment();
    case 1:
        // Games fragment activity
        return new ImageFragment();
    case 2:
        // Movies fragment activity
        return new TextFragment();
    case 3:
        return new Test();
    }

    return null;
}

@Override
public int getCount() {
    // get item count - equal to number of tabs
    return 4;
}

MainActivity

       public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {

private TabsPagerAdapter mAdapter;
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();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
    // Fragments and ViewPager Initialization


    mViewPager.setAdapter(mAdapter);
    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) {

}


// 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("ButtonTab").setIndicator("ButtonTab"));
    MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("ImageTab").setIndicator("ImageTab"));
    MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("TextTab").setIndicator("TextTab"));
    MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("TestingTab").setIndicator("TestingTab"));

    mTabHost.setOnTabChangedListener(this);
}

2 个答案:

答案 0 :(得分:3)

这是viewpager的默认行为,您无法更改它,因为viewpager会创建片段以便存在视图,因此用户可以在它们之间滑动,以便旧视图滑出屏幕并将新视图滑动到屏幕上。您可以像这样编写代码

 @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
          Log.i("inside", "button fragment");
        }else{
           // fragment is not visible
        }
    } 

这样当片段可见时,您的代码就会执行

答案 1 :(得分:1)

更改标签时,请调出相应的片段。 试试这个会帮到你

创建TabFragment.java

public class TabFragment extends Fragment implements OnPageChangeListener,
    OnTabChangeListener {
private TabHost tabHost;
private int currentTab = 0;
private SwipeDisableViewPager viewPager;
protected TabPagerAdapter pageAdapter;
private List<Fragment> fragments;
private final int TAB_BUTTON=0,TAB_IMAGE=1,TAB_TEXT=2,TAB_TEST=3;

@SuppressWarnings("unchecked")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_tabhost, null);
    viewPager = (SwipeDisableViewPager) view.findViewById(R.id.viewpager);
    tabHost = (TabHost) view.findViewById(android.R.id.tabhost);
    viewPager.addOnPageChangeListener(this);
    fragments = new ArrayList<>();
    fragments.add(new ButtonFragment());
    fragments.add(new ImageFragment());
    fragments.add(new TextFragment());
    fragments.add(new Test());
    return view;
}


@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    pageAdapter = new TabPagerAdapter(getChildFragmentManager(), fragments, getArguments());
    pageAdapter.notifyDataSetChanged();
    viewPager.setAdapter(pageAdapter);
    viewPager.setOffscreenPageLimit(3);
    setupTabs();
}


private void setupTabs() {
    tabHost.setup();
    tabHost.addTab(newTab(R.string.home, R.drawable.menu_home_bg));
    tabHost.addTab(newTab(R.string.likes, R.drawable.menu_likes_bg));
    tabHost.addTab(newTab(R.string.matches, R.drawable.menu_matches_bg));
    for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
        tabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);

    }
    tabHost.setOnTabChangedListener(this);
    tabHost.setCurrentTab(currentTab);
}

private View getTabIndicator(Context context, int title, int icon) {
    View view = LayoutInflater.from(context).inflate(R.layout.tab_view, null);
    ImageView iv = (ImageView) view.findViewById(R.id.imageView);
    iv.setImageResource(icon);
    TextView tv = (TextView) view.findViewById(R.id.textView);
    tv.setText(title);
    return view;
}

private TabSpec newTab(int tabValue, int icon) {
    TabSpec tabSpec = tabHost.newTabSpec(getString(tabValue));
    tabSpec.setIndicator(getTabIndicator(tabHost.getContext(), tabValue, icon));
    tabSpec.setContent(new Dummy(getActivity()));
    return tabSpec;
}

@Override
public void onPageScrollStateChanged(int arg0) {

}

@Override
public void onPageScrolled(int currentPosition, float arg1, int arg2) {

}

@Override
public void onPageSelected(int position) {
    if (position == 0)
        viewPager.setSwipeEnabled(false);
    else
        viewPager.setSwipeEnabled(true);
    tabHost.setCurrentTab(position);
    if (listener != null)
        listener.onTabChanged(position);
}

@Override
public void onTabChanged(String tabId) {
    currentTab = tabHost.getCurrentTab();
    viewPager.setCurrentItem(currentTab);
    switch(currentTab){
      case TAB_BUTTON:
        ((ButtonFragment) fragments.get(currentTab)).recall();
      break;
      case TAB_IMAGE:
        ((ImageFragment) fragments.get(currentTab)).recall();
      break;
      case TAB_TEXT:
        ((TextFragment) fragments.get(currentTab)).recall();
      break;
      case TAB_TEST:
        ((Test) fragments.get(currentTab)).recall();
      break;        
}
}

创建tab_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<TabHost 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:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@drawable/menu_bg"
        android:fadingEdge="none"
        android:gravity="center"
        android:showDividers="none"
        android:tabStripEnabled="false" />

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="0" />

    <com.mobellotech.shift.Widget.SwipeDisableViewPager
        android:id="@+id/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="#FFFFFF" />
</LinearLayout>
</TabHost>

创建tab_view.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="45dp"
android:layout_height="45dp"
    android:contentDescription="@string/menu_icon" />

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

创建TabPagerAdaper

public class TabPagerAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;

public TabPagerAdapter(FragmentManager fm, List<Fragment> fragments,
                       Bundle args) {
    super(fm);
    this.fragments = fragments;
    this.args = args;
}

@Override
public Fragment getItem(int position) {
    Fragment fragment = fragments.get(position);
    fragment.setArguments(args);
    return fragment;
}

@Override
public int getCount() {
    return fragments.size();
}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}
}

创建MainActivity.java

public class MainActivity extends AppCompatActivity  {

protected TabFragment tabFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tabFragment = new TabFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.frame_container, tabFragment).commit();
}
}

创建activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
      />
</android.support.v4.widget.DrawerLayout>

最后在您的片段类中添加召回方法,如

public class ButtonFragment extends Fragment {

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

View rootView = inflater.inflate(R.layout.fragment_button, container, false);
Log.i("inside", "button fragment");
return rootView;
}
 public void recall() {
     Log.i("inside", "button fragment");
 }
}