无法在ViewPager中的片段中编辑ActionBar标题

时间:2019-02-04 14:08:59

标签: java android android-layout android-fragments android-viewpager

我有一个Activity,它通过ViewPager托管多个片段。在活动的onCreate方法中,我使用以下代码更改ActionBar标题:

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if(getSupportActionBar() != null) {
        getSupportActionBar().setTitle(getResources().getString(R.string.custom_title));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

它可以正常工作,但是一旦Fragment出现,我便无法更改它。为了检测到它,我已经实现了:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {

    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser && getContext() != null) {
            ((MainActivity) getContext()).editActionBarTitle("new title");
    }
}

这是editActionBarTitle的定义:

public void editActionBarTitle(String title) {
     if(getSupportActionBar() != null) {
         getSupportActionBar().setTitle(title);
         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
     }
}

我可以看到,只要有一个片段可见,该方法就会被调用,但是它对ActionBar的标题没有影响。为了正确编辑标题,我缺少什么?


编辑

我也尝试过在addOnPageChangeListener中实现viewPager,我可以看到方法onPageSelected被调用了,但是对标题没有影响,这是MainActivity的一个例子:

public class MainActivity extends BaseActivity {   

    private NoScrollViewPager mViewPager;
    private SectionsPagerAdapter mAdapter;

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

        // Toolbar initialization
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if(getSupportActionBar() != null) {
            getSupportActionBar().setTitle("MainActivity");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        // ViewPager initialization
        mViewPager = findViewById(R.id.containter);
        setupViewPager();
    }

    private void setupViewPager() {

        mAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mAdapter.addFragment(new Fragment1(), "Fragment 1");
        mAdapter.addFragment(new Fragment2(), "Fragment 2");
        mAdapter.addFragment(new Fragment3(), "Fragment 3");

        mViewPager.setOffscreenPageLimit(mAdapter.getCount());
        mViewPager.setAdapter(mAdapter);

        // viewPager event listener
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

            @Override
            public void onPageSelected(int position) {
                setTitle("fragment " + position);
                if(getSupportActionBar() != null) {
                    getSupportActionBar().setTitle("fragment " + position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) { }
        });
    }

    public void setViewPager(int position) { mViewPager.setCurrentItem(position); }
}

这是自定义ViewPager类:

public class NoScrollViewPager extends ViewPager {

    // Disable horizontal scrolling in ViewPager
    private boolean isPagingEnabled = false;

    public NoScrollViewPager(Context context) {
        super(context);
    }

    public NoScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    @SuppressLint("AndroidLintClickableViewAccessibility")
    public boolean onTouchEvent(MotionEvent event) {
        return this.isPagingEnabled && super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return this.isPagingEnabled && super.onInterceptTouchEvent(event);
    }

    public void setPagingEnabled(boolean b) {
        this.isPagingEnabled = b;
    }
}

这是自定义Adapter类:

public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    private FragmentManager fragmentManager;

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

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public Fragment getItem(int position) { return mFragmentList.get(position); }

    @Override
    public int getCount() { return mFragmentList.size(); }

    @Override
    public int getItemPosition(Object object) { return POSITION_NONE; }

}

6 个答案:

答案 0 :(得分:6)

在您的onCreateView方法中尝试将其片段化。也许会对您有帮助。

if(getActivity() != null){
     getActivity().setTitle("Your title");
}

如果您在片段中使用ViewPager,则可以使用

@Override
    public void setUserVisibleHint(boolean isVisible) {
        super.setUserVisibleHint(isVisible);

        if (isVisible) {
            if(getActivity() != null){
               getActivity().setTitle("Your title");
            }
        }
    }

答案 1 :(得分:4)

您也可以使用viewPager.addOnPageChangeListener()

  • 添加一个侦听器,只要页面发生更改或逐步滚动,就会调用该侦听器

viewPager.addOnPageChangeListener()中,您需要在 actionbar

中的onPageSelected()中设置标题

返回当前viewpager中当前选择的页面

示例代码

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        @Override
        public void onPageSelected(int i) {

            if (i == 0) {
                getSupportActionBar().setTitle("Fragment One");
            } else if (i == 1) {
                getSupportActionBar().setTitle("Fragment Two");
            } else if (i == 2) {
                getSupportActionBar().setTitle("Fragment three");
            } else if (i == 3) {
                getSupportActionBar().setTitle("Fragment four");
            } else if (i == 4) {
                getSupportActionBar().setTitle("Fragment Five");
            }

        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });

这是我的工作代码

  

活动代码

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;


public class HomeActivity extends AppCompatActivity {


    private NoScrollViewPager mViewPager;
    private SectionsPagerAdapter mAdapter;


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

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

        getSupportActionBar().setTitle("Fragment One");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // ViewPager initialization
        mViewPager = findViewById(R.id.containter);

        findViewById(R.id.btnOne).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewPager.setCurrentItem(0);
            }
        });
        findViewById(R.id.btnTwo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewPager.setCurrentItem(1);
            }
        });
        findViewById(R.id.btnThree).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewPager.setCurrentItem(2);
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {

                if (i == 0) {
                    getSupportActionBar().setTitle("Fragment One");
                } else if (i == 1) {
                    getSupportActionBar().setTitle("Fragment Two");
                } else if (i == 2) {
                    getSupportActionBar().setTitle("Fragment three");
                }

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });


        setupViewPager();


    }

    private void setupViewPager() {

        mAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mAdapter.addFragment(new Fragment1(), "Fragment 1");
        mAdapter.addFragment(new Fragment2(), "Fragment 2");
        mAdapter.addFragment(new Fragment3(), "Fragment 3");

        mViewPager.setOffscreenPageLimit(mAdapter.getCount());
        mViewPager.setAdapter(mAdapter);

        // viewPager event listener
    }


}
  

布局

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <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/ThemeOverlay.AppCompat.Light" />

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnOne"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Frag 1" />

        <Button
            android:id="@+id/btnTwo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Frag 2" />


        <Button
            android:id="@+id/btnThree"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Frag 3" />

    </LinearLayout>

    <neel.com.demo.NoScrollViewPager
        android:id="@+id/containter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

输出

https://www.youtube.com/watch?v=ytJogOkj1zQ

答案 2 :(得分:1)

了解FragmentAViewPager中显示的唯一合法方法是对OnPageChangeListener回调进行反应。

采用this answer中提到的技术,您可能最终得到以下代码:

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(final int i) {
            MyAdapter adapter = ((MyAdapter) viewPager.getAdapter());
            TitleOwner titleOwner = adapter.getTitleOwner(index);
            String title = titleOwner.getTitle();
            getSupportActionBar().setTitle(title);
        }

        @Override
        public void onPageScrollStateChanged(final int i) {
        }

        @Override
        public void onPageScrolled(final int i,final float v,final int i1) {
        }
});

这假设ViewPager中显示的所有片段都实现了TitleOwner

interface TitleOwner {
    String getTitle();
}

和片段类:

class MainScreenFragment extends Fragment implements TitleOwner {
    ...
    @Override
    public String getTitle() {
        return "Main Screen";
    }
}

答案 3 :(得分:0)

能否请您检查是否正在使用NoActionBar主题。例如Theme.AppCompat.Light.NoActionBarTheme.MaterialComponents.NoActionBar

答案 4 :(得分:0)

我最近的一个项目中遇到了这个问题。最后,我为每个片段都有自己的标题设计了单独的工具栏。我确实使用过:

Theme.MaterialComponents.NoActionBar

答案 5 :(得分:0)

更改onPageSelected中的代码

setTitle("fragment " + position);
if(getSupportActionBar() != null) {
    getSupportActionBar().setTitle("fragment " + position);
}

对此

toolbar.setTitle(title);

并扩展AppCompatActivity而不是BaseActivity。 在onCreate中保留相同的代码