SlidingTabLayout和Actionbar标题

时间:2015-09-22 11:30:22

标签: android android-fragments android-adapter pagertabstrip

我在我的应用中使用SlidingTabLayout(来自Google来源)在不同的片段之间导航。 我可以在内容之间滑动就好了,但我面临的问题是动作栏的标题,表现得很奇怪。

假设我有两个带有两个标题的标签(' First Title'' Second Title'):

| Action bar       |

| First Title | Second Title |

当我第一次输入包含SlidingTabLayout的片段时,Actionbar的标题是这样的:

| Firs...      |

| First Title | Second Title |

当我滑动(例如,第二个标签)时,操作栏的标题变为:

| Second Title       |

| First Title | Second Title |

并保持这样。当我至少滑动一次时,似乎Actionbar会加载最后一个片段的标题

我想要的是:

我想要显示一个'主标题'在操作栏中,无论SlidingTabLayout中的标题是什么,都不会发生变化。

以下是我的代码的一些部分:

**包含SlidingTabLayout的片段:

private String mainTitle;
....

@Override
public void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);

    // The mainTitle is given to this fragment by another fragment
    Bundle args = getArguments();
    if (args != null) {
        mainTitle = args.getString("TITLE");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.layout, container, false);
    mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
    mSlidingLayout = (SlidingTabLayout) rootView.findViewById(R.id.sliding_layout);
    List<Fragment> listFragments = new ArrayList<>();
    List<String> listTitles = new ArrayList<>();
    for (int i = 0; i < mSize; i++) {
        Bundle bundle = new Bundle();
        ....
        listFragments.add(Fragment.instanciate(getActivity(), CustomFragment.class.getName(), bundle));
        listTitles.add("...");
    }
    mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), listFragments, listTitles));

    mSlidingLayout.setDistributedEvenly(true);
    mSlidingLayout.setViewPager(mViewPager);

    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    // I TRY TO SET THE TITLE HERE !!
    getActivity().getSupportActionBar().setTitle(mainTitle);
}

**适配器:

class PagerAdapter extends FragmentPagerAdapter {
    List<Fragment> fragments;
    List<String> titles;
    ...
    @Override
    public Fragment getItem(int position) {
        Fragment fragment = fragments.get(position);
        return fragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        // maybe the problem is in this method.
        // this method is supposed to provide the titles for the tab
        // but maybe it's also changing the actionbar title
        return titles.get(position);
}

每次输入片段时,我都会在onResume方法中设置ActionBar的标题。

谢谢!

编辑1:

我尝试使用我从Google I / O获得的新SlidingTabLayout,结果仍然相同!

似乎ActionBar中的Title首先是一个提示,然后当我滑动到另一个片段时它会更改为最后加载的片段。

它就像加载片段一样,每次加载片段时,ActionBar中的标题都会被该片段的标题覆盖。

编辑2:

我更改了我的代码以发布它的最新版本(我现在使用SlidingTabLayout)并显示我如何获得我的mainTitle。

4 个答案:

答案 0 :(得分:1)

你可以使用下面的代码,它对我来说很好用

public class MatchesActivity extends AppCompatActivity implements ActionBar.TabListener {

SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
FloatingActionButton skipButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_matches);
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowHomeEnabled(true);
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    skipButton = (FloatingActionButton) findViewById(R.id.skip_next);
    skipButton.setVisibility(View.GONE);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOffscreenPageLimit(1);
    mViewPager.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return false;
        }
    });
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    actionBar.addTab(
            actionBar.newTab().setText("MATCHES")
                    .setTabListener(this));
    actionBar.addTab(
            actionBar.newTab().setText("PINS")
                    .setTabListener(this));
    actionBar.addTab(
            actionBar.newTab().setText("CHATS")
                    .setTabListener(this));
}

@Override
public void onBackPressed() {
    startActivity(new Intent(MatchesActivity.this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK & Intent.FLAG_ACTIVITY_CLEAR_TOP));
    MatchesActivity.this.finish();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        onBackPressed();
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    mViewPager.setCurrentItem(tab.getPosition());
}

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

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

public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new MatchesFragment();
            case 1:
                return new PinsFragment();
            case 2:
                return new ConversationFragment();
            default:
                return new MatchesFragment();
        }
    }

    @Override
    public int getCount() {
        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;
    }
}

}

答案 1 :(得分:1)

我在这里发布了一个我的代码。它对我有用。需要对其进行修改并尝试。我在其中使用了PagerSlidingTabStrip库。

public class DealFragment extends Fragment {


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.fragment_deal, container, false);
    ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    viewPager.setAdapter(new SampleFragmentPagerAdapter(getChildFragmentManager()));
    PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip)view.findViewById(R.id.tabs);
    tabsStrip.setBackgroundColor(Color.parseColor("#333333"));
    // Attach the view pager to the tab strip
    tabsStrip.setViewPager(viewPager);
    return view;
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
    final int PAGE_COUNT = 2;
    private final String tabTitles[] = new String[] { "Today's Deals", "Deals Close By" };

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

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }

    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        if(position==0)
        {
            return new TodaysDeal();
        }
        else
        {
            return new DealsCloseBy();
        }

    }

    @Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        return tabTitles[position];
    }
}

}

希望它可以帮到你。

答案 2 :(得分:1)

actionBar标题不会更改,因为您向后滑动时不会调用onResume()

这是因为ViewPager第二次不调用片段onResume。即使实际上片段已恢复。

您可以做的是将父片段(包含pagertabstrip)中的操作栏标题设置移至onCreateView

供您参考:

**包含PagerTabStrip的片段:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.layout, container, false);
    mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);

    List<Fragment> listFragments = new ArrayList<>();
    List<String> listTitles = new ArrayList<>();

    ...

    // HERE's what you want
    final ActionBar actionBar = getActivity().getSupportActionBar();
    if (actionBar != null) {
        actionBar.setTitle(R.string.main_title);
    }

    mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), listFragments));

    return rootView;
}

答案 3 :(得分:0)

发现它!

我真傻(这解释了为什么其他人没有这个问题)

我也在每个片段(甚至包含在标签中的片段)中设置了标题,所以当我滑动时,这些片段上的onResume被调用并且它改变了ActionBar中的标题......

谢谢大家的帮助,我很感激!