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

Tabs execute the codes present in their next fragments in android

我正在尝试使用 ViewPager 和 4 Fragments 通过滑动实现 Tabs。当我滑动选项卡时,每个选项卡上都会正确显示相应的 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-测试 public class 测试扩展片段 {

@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 的日志消息。滑动到选项卡 2 后,我收到选项卡 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);
}

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

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

以便在片段可见时执行您的代码

当你改变你的标签时,调用你相应的片段。 试试这个对你有帮助

创建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>

最后在你的片段中添加召回方法class像这样

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