简体   繁体   English

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

[英]Fragment set toolbar title but the next fragment title is shown

I am pretty new to Android development and I am trying to make a tabbed activity where the title changes according to the fragment. 我是Android开发的新手,我正在尝试制作一个选项卡式活动,标题根据片段而变化。 I tried using the following code which I found online, but when the first fragment is loaded, the second fragment title is shown at the toolbar instead. 我尝试使用以下在网上找到的代码,但是当加载第一个片段时,第二个片段标题将显示在工具栏上。

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

One of the Fragment codes: 片段代码之一:

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

The Tabbed Activity XML: 选项卡式活动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>

Any help is truly appreciated. 任何帮助,我们都感激不尽。

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public String[] tabtitles = {"fag1", "frag2", "frag3", "farg4", "farg5"};

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

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new Fragment1();
                break;
            case 1:
                fragment = new Fragment2();
                break;
            case 2:
                fragment = new Fragment3();
                break;
            case 3:
                fragment = new Fragment4();
                break;
            case 4:
                fragment = new Fragment5();
                break;

            default:
                break;
        }
        // Return a PlaceholderFragment (defined as a static inner class below).
        return fragment;
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 5;
    }


    @Override
    public CharSequence getPageTitle(int position) {
        return tabtitles[position];
    }
}

Figure out that the ViewPager is created, the first tab is created and the second tab is created also(for performance reason or something else, see setOffscreenPageLimit method( the default value is 1 )). ViewPager已创建ViewPager还创建了第一个选项卡,还创建了第二个选项卡(出于性能原因或其他原因,请参见setOffscreenPageLimit方法( 默认值为1 ))。 So, the second tab is created after the first one. 因此,第二个选项卡在第一个选项卡之后创建。 This is the reason why the text of the second tab is displayed. 这就是为什么显示第二个选项卡的文本的原因。

You should check which tab is displaying before updating the title 您应该先检查显示哪个标签,然后再更新标题

Hopes it helps 希望能有所帮助

You can try this . 你可以试试看。

1.use addOnTabSelectedListener addOnTabSelectedListener

2.when onTabSelected is selected , you can setToolbarTitle(mTitleNames[pos]); 2.当选择onTabSelected ,可以设置setToolbarTitle(mTitleNames[pos]);

3.and remove ((TabbedActivity)getActivity()).toolbar.setTitle("Fragment 1"); 3.并删除((TabbedActivity)getActivity()).toolbar.setTitle("Fragment 1"); in your fragment 在你的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);
}

Use below code and your problem will be solved: 使用下面的代码,您的问题将得到解决:

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

    }
}

I have tested this code and it works fine, check image. 我已经测试了此代码,它工作正常,请检查图像。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM