如何获取已选择的片段

时间:2013-06-20 09:55:53

标签: android android-fragments android-tabs

我正在使用片段创建一个标签应用程序。

我已经成功创建了标签,但现在我需要在选择特定片段时创建一个对象。例如当我选择SettingsTab时,我需要调用Test class中定义的函数。并同样销毁

// SettingsTab
package com.example.sensorspositioningn;

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

public class SettingsTab extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.settingstab, container, false);

    }
}

以下是mainActivity中的代码:

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


        appContext = getApplicationContext();

        //ActionBar
        ActionBar actionbar = getActionBar();
        actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        ActionBar.Tab Tab1= actionbar.newTab().setText("Tab1");
        ActionBar.Tab Tab2= actionbar.newTab().setText("Tab2");
        ActionBar.Tab Tab3= actionbar.newTab().setText("Tab3");
        ActionBar.Tab SettingsTab = actionbar.newTab().setText("Settings");

        Fragment Tab1F= new Tab1();
        Fragment Tab2F= new Tab2();
        Fragment Tab3F= new Tab3();
        Fragment mSettingsFragment = new SettingsTab();

        Tab1.setTabListener(new MyTabsListener(Tab1F));
        Tab1.setTabListener(new MyTabsListener(Tab2F));
        Tab1.setTabListener(new MyTabsListener(Tab3F));
        SettingsTab.setTabListener(new MyTabsListener(mSettingsFragment));

        actionbar.addTab(Tab1);
        actionbar.addTab(Tab2);
        actionbar.addTab(Tab3);
        actionbar.addTab(SettingsTab);


    }
protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
    }

class MyTabsListener implements ActionBar.TabListener {
        public Fragment fragment;

        public MyTabsListener(Fragment fragment) {
            this.fragment = fragment;
        }


        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
        }


        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            ft.replace(R.id.fragment_container, fragment);




        }


        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            ft.remove(fragment);


        }
    }

4 个答案:

答案 0 :(得分:8)

ActionBar.TabListener你可以这样做 - (我假设你需要对象在Activity

class MyTabsListener implements ActionBar.TabListener {
    public Fragment fragment;

    public MyTabsListener(Fragment fragment) {
        this.fragment = fragment;
    }


    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
    }


    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.replace(R.id.fragment_container, fragment);

        if(fragment instanceof SettingsTab) {
            // Create your object, call your function
        }
    }


    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(fragment);

        if(fragment instanceof SettingsTab) {
            // Destroy your object
        }
    }
}

答案 1 :(得分:2)

试试这个

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.replace(R.id.fragment_container, fragment);

        if(fragment instanceof SettingsTab){
            doSettingsMethod();
        }

        if(fragment instanceof Tab1){
            doOtherMethod1();
        }

        if(fragment instanceof Tab2){
            doOtherMethod2();
        }

        if(fragment instanceof Tab3){
            doOtherMethod3();
        }
    }

此外,您可以通过这种方式更改TabListener类。至于我,这是一个更好的设计。

class MyTabsListener implements ActionBar.TabListener {
    public Fragment fragment;
    private final Runnable onSelect;

    public MyTabsListener(Fragment fragment) {
        this.fragment = fragment;
        this.onSelect = null;
    }

    public MyTabsListener(Fragment fragment, Runnable onSelect) {
        this.fragment = fragment;
        this.onSelect = onSelect;
    }


    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
    }


    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.replace(R.id.fragment_container, fragment);
        if(onSelect != null){
            fragment.getActivity().runOnUiThread(onSelect);
        }
    }


    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(fragment);


    }
}

答案 2 :(得分:2)

我发现的唯一官方来源是开发者网站: http://developer.android.com/training/implementing-navigation/lateral.html

他们只是为每个创建的片段添加参数,并在片段被选中时读取参数。

答案 3 :(得分:0)

默认情况下,如果您选择一个标签,它将突出显示。如果要选择显式,请使用指定选项卡索引位置的onTabSelected(TabLayout.Tab选项卡)下的给定注释代码。此代码将使用viewpager解释选项卡选定位置上的更改片段。

public class GalleryFragment extends Fragment implements TabLayout.OnTabSelectedListener 
{
private ViewPager viewPager;public ViewPagerAdapter adapter;private TabLayout tabLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new PaymentCardFragment(), "PAYMENT CARDS");
adapter.addFragment(new LoyaltyCardFragment(), "LOYALTY CARDS");
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.setOnTabSelectedListener(this);
}

@Override
public void onTabSelected(TabLayout.Tab tab) {
    //This will be called 2nd when you select a tab or swipe using viewpager
    final int position = tab.getPosition();
    Log.i("card", "Tablayout pos: " + position);
    //TabLayout.Tab tabdata=tabLayout.getTabAt(position);
    //tabdata.select();
    tabLayout.post(new Runnable() {
        @Override
        public void run() {
            if (position == 0) {
                PaymentCardFragment paymentCardFragment = getPaymentCardFragment();
                if (paymentCardFragment != null) {
                   VerticalViewpager vp = paymentCardFragment.mypager;
                    if(vp!=null)
                    {
                      //vp.setCurrentItem(position,true);
                      vp.setCurrentItem(vp.getAdapter().getCount()-1,true);
                    }
                  }
            }
            if (position == 1) {
               LoyaltyCardFragment loyaltyCardFragment = getLoyaltyCardFragment();
                if (loyaltyCardFragment != null) {
                   VerticalViewpager vp = loyaltyCardFragment.mypager;
                    if(vp!=null)
                    {
                        vp.setCurrentItem(position);
                    }
                  }
            }
        }
    });
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {
 //This will be called 1st when you select a tab or swipe using viewpager
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
  //This will be called only when you select the already selected tab(Ex: selecting 3rd tab again and again)
}
 private PaymentCardFragment getLoyaltyCardFragment() {
    Fragment f = adapter.mFragmentList.get(viewPager.getCurrentItem());

   if(f instanceof PaymentCardFragment)
   {
    return (PaymentCardFragment) f;
   }
   return null;
 }
private LoyaltyCardFragment getPaymentCardFragment() {
    Fragment f = adapter.mFragmentList.get(viewPager.getCurrentItem());
    if(f instanceof LoyaltyCardFragment)
   {
    return (LoyaltyCardFragment) f;
   }
   return null;
 }
  class ViewPagerAdapter extends FragmentPagerAdapter {
   public List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();
   public void addFragment(Fragment fragment, String title) {
   mFragmentList.add(fragment);
   mFragmentTitleList.add(title);
  }
 }
}