问题描述
我有一个 ViewPager
,我使用 switch 和 case
在片段之间移动.我可以更改每个位置的标题,但我也想更改每个位置的背景颜色.
I have a ViewPager
, and I move between fragments using a switch and case
. I can change the title per position, but I would also like to change the background colour per position.
public PagerTabStrip titleStrip;
titleStrip.setBackgroundColor(Color.DKGRAY);
在我的 onCreateView 中使用它会设置一个永久的背景颜色.我的想法是使用 titleStrip.setBackgroundColor(Color.DKGRAY);我在哪里切换片段或更改标题.但它不能正常工作.有时颜色会改变,有时不会,有时会在错误的片段中改变.
Using this in my onCreateView sets a permanent background colour. The idea I had was to use the titleStrip.setBackgroundColor(Color.DKGRAY); where I switch the fragments or change the title. But it doesn't work properly. Sometimes the colour changes, sometimes it doesn't, sometimes it changes in the wrong fragment.
这是我切换片段的代码:
This is the code where I switch fragments:
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: titleStrip.setBackgroundColor(Color.DKGRAY); // These
titleStrip.setTextColor(Color.WHITE); // This doesn't work either
return new Fragment0();
case 1:
return new Fragment1();
case 2:
return new Fragment3();
}
return null;
}
推荐答案
首先,让你在createView
时得到titleStrip
:
titleStrip = (PagerTabStrip) pagerView.findViewById(R.id.pager_title_strip);
然后,你可以添加OnPageChangeListener
到ViewPager
,你可以在onPageSelected方法中做任何你想做的事情:
then, you can add OnPageChangeListener
to ViewPager
, you can do anything you want in onPageSelected method:
mPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
switch (position) {
case 0:
titleStrip.setBackgroundColor(Color.BLUE);
break;
case 1:
titleStrip.setBackgroundColor(Color.GRAY);
break;
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
这篇关于使用位置更改 PagerTabStrip 的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!