2016-08-13 147 views
0

我正在開發一個具有3個選項卡的android應用程序。我正在使用TabLayoutViewPager。我計劃在3個不同的選項卡上爲AppBar & TabLayout提供3種不同的背景顏色。我需要通過滾動或單擊選項卡來更改標籤頁之間的平滑過渡。你如何進行這種轉變?有誰能夠幫助我?滾動時更改Tablayout背景顏色

回答

2

我製作樣品。希望這可以幫助。

enter image description here

在你的活動:

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

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); 
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout); 

    int[] colors = {Color.RED, Color.GREEN, Color.BLUE}; 
    viewPager.setAdapter(new MyAdapter()); 
    viewPager.addOnPageChangeListener(new HeaderColorChanger(tabLayout, colors)); 
    tabLayout.setupWithViewPager(viewPager); 
} 

MyAdapter是這樣的:

class MyAdapter extends PagerAdapter { 

    @Override 
    public Object instantiateItem(ViewGroup container, int position) { 
     TextView view = (TextView) LayoutInflater 
       .from(container.getContext()) 
       .inflate(R.layout.row_item, container, false); 
     container.addView(view); 
     view.setText("Page:" + position); 
     return view; 
    } 

    @Override 
    public void destroyItem(ViewGroup container, int position, Object object) { 
     container.removeView((View) object); 
    } 

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

    @Override 
    public boolean isViewFromObject(View view, Object object) { 
     return view == object; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     return "Page:" + position; 
    } 
} 

HeaderColorChanger是這樣的:

class HeaderColorChanger implements ViewPager.OnPageChangeListener { 

    private ArgbEvaluator argbEvaluator = new ArgbEvaluator(); 
    private View mView; 
    private int[] mColors; 

    HeaderColorChanger(View view, int[] colors) { 
     mView = view; 
     mColors = colors; 
    } 

    @Override 
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 
     mView.setBackgroundColor(getHeaderColor(position, positionOffset)); 
    } 

    @Override 
    public void onPageSelected(int position) { 
    } 

    @Override 
    public void onPageScrollStateChanged(int state) { 

    } 

    private int getHeaderColor(int position, float positionOffset) { 
     if (position == mColors.length - 1) { 
      return mColors[position]; 
     } 
     int startColor = mColors[position]; 
     int endColor = mColors[position + 1]; 
     int color = (int) argbEvaluator.evaluate(positionOffset, startColor, endColor); 
     return color; 
    } 
}