片段设置工具栏标题,但显示下一个片段标题

时间:2017-11-25 03:06:25

标签: java android android-fragments

我对Android开发很新,我正在尝试根据片段进行标题更改的标签式活动。我尝试使用我在网上找到的以下代码,但是当加载第一个片段时,第二个片段标题会显示在工具栏上。

public class TabbedActivity extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public Toolbar toolbar;

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

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

    tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        switch(position){
            case 0:
                return new FragmentActivity_1();
            case 1:
                return new FragmentActivity_2();
            case 2:
                return new FragmentActivity_3();
            case 3:
                return new FragmentActivity_4();
            case 4:
                return new FragmentActivity_5();
        }
        return null;
    }

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

其中一个片段代码:

public class FragmentActivity_chat extends Fragment{

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
    View view = inflater.inflate(R.layout.chat_tabbed, container, false);

    ((TabbedActivity)getActivity()).toolbar.setTitle("Fragment 1");

    return view;
}
}

选项卡式活动XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.android.MyApp.TabbedActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:title="@string/app_name">

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryLight"
        app:tabMode="fixed"
        app:tabGravity="fill">

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:icon="@drawable/ic_person_black_24dp"/>

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:icon="@drawable/ic_chat_black_24dp"/>

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:icon="@drawable/ic_location_on_black_24dp"/>

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:icon="@drawable/ic_group_black_24dp"/>

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:icon="@drawable/ic_settings_black_24dp"/>

    </android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

真的很感激任何帮助。

3 个答案:

答案 0 :(得分:0)

确定创建了ViewPager,创建了第一个标签,同时创建了第二个标签(出于性能原因或其他原因,请参阅setOffscreenPageLimit方法(默认值为1 ))。因此,第二个选项卡是在第一个选项卡之后创建的。这就是显示第二个选项卡文本的原因。

在更新标题之前,您应该检查显示哪个标签

希望有所帮助

答案 1 :(得分:0)

你可以试试这个。

1.使用addOnTabSelectedListener

2.选择onTabSelected后,您可以setToolbarTitle(mTitleNames[pos]);

3.并删除((TabbedActivity)getActivity()).toolbar.setTitle("Fragment 1");

中的fragment
final String[] mTitleNames = {"Fragment 1", "Fragment 2", "Fragment 3", "Fragment 4","Fragment 5"};

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

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    // set default title
    setActionBarTitle(mTitleNames[0]);
    // add here
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            int pos = tab.getPosition();
            setToolbarTitle(mTitleNames[pos]);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
}

/**
 * set toolbar title
 * @param title
 */
public void setToolbarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

答案 2 :(得分:0)

使用以下代码,您的问题将得到解决:

public class TabbedActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    public Toolbar toolbar;
    public String[] tabtitles = {"FragmentActivity_1", "FragmentActivity_2", "FragmentActivity_3", "FragmentActivity_4", "FragmentActivity_5"};
    public int[] icons = {R.mipmap.ic_launcher_round, R.mipmap.ic_launcher_round, R.mipmap.ic_launcher_round, R.mipmap.ic_launcher_round, R.mipmap.ic_launcher_round};

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

        tabLayout.setupWithViewPager(mViewPager);
        setTabIcon(tabLayout);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                getSupportActionBar().setTitle(tabtitles[position]);

            }

            @Override
            public void onPageSelected(int position) {
                getSupportActionBar().setTitle(tabtitles[position]);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    private void setTabIcon(TabLayout tabLayout) {
        int count = tabLayout.getTabCount();
        for (int i = 0; i < count; i++) {
            tabLayout.getTabAt(i).setIcon(icons[i]);
        }
    }


    public class SectionsPagerAdapter extends FragmentPagerAdapter {


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

        @Override
        public Fragment getItem(int position) {

            Fragment fragment = null;

            switch (position) {
                case 0:
                    fragment = new FragmentActivity_1();
                    break;
                case 1:
                    fragment = new FragmentActivity_2();
                    break;
                case 2:
                    fragment = new FragmentActivity_3();
                    break;
                case 3:
                    fragment = new FragmentActivity_4();
                    break;
                case 4:
                    fragment = new FragmentActivity_5();
                    break;
                default:
                    fragment = new FragmentActivity_1();
                    break;
            }
            return fragment;
        }

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

    }
}

我已经测试了这段代码并且工作正常,请检查图片。

enter image description here