我有一个 ViewPager
,我使用的是开关和案例
片段之间移动。我可以改变每个位置上的冠军,但我也想改变,每个位置的背景颜色。
公共PagerTabStrip titleStrip;
titleStrip.setBackgroundColor(Color.DKGRAY);
在我onCreateView使用此设置一个永久性的背景色。我当时的想法是使用titleStrip.setBackgroundColor(Color.DKGRAY);我的切换碎片或更改标题。但它不能正常工作。有时颜色的变化,有时不,有时它改变了错误的片段。
这是在code,我切换片段:
@覆盖
公共片段的getItem(INT位置){
开关(位置){
情况下0:titleStrip.setBackgroundColor(Color.DKGRAY); // 这些
titleStrip.setTextColor(Color.WHITE); //这也不起作用
返回新Fragment0();
情况1:
返回新片段1();
案例2:
返回新Fragment3();
}
返回null;
}
解决方案
首先,发售者,你已经拿到了 titleStrip
在 CreateView的
:
titleStrip =(PagerTabStrip)pagerView.findViewById(R.id.pager_title_strip);
那么,你可以添加 OnPageChangeListener
到 ViewPager
,你可以做你想做的onPageSelected方法什么:
mPager.setOnPageChangeListener(新OnPageChangeListener(){
@覆盖
公共无效onPageSelected(INT位置){
开关(位置){
情况下0:
titleStrip.setBackgroundColor(Color.BLUE);
打破;
情况1:
titleStrip.setBackgroundColor(Color.GRAY);
打破;
}
}
@覆盖
公共无效onPageScrolled(INT位置,浮positionOffset,诠释positionOffsetPixels){
}
@覆盖
公共无效onPageScrollStateChanged(INT状态){
}
});
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);
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;
}
解决方案
First, make suer you have got the titleStrip
when createView
:
titleStrip = (PagerTabStrip) pagerView.findViewById(R.id.pager_title_strip);
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) {
}
});