The following knowledge points, is their first time to do this effect, record the knowledge, do not know whether there is a better way to achieve.

In some Android projects, there are small images on top of the guide page. The background color is solid, and each color is different. As a result, the color change of the switching effect feels stiff when sliding the guide page. This article explains how to implement an effect that gradually changes the background color based on sliding. Take a look at the renderings, as follows:




Effect display diagram

1. Main dependence: The compile ‘com. Android. Support: support – v4:23.4.0’ compile ‘com. Readystatesoftware. Systembartint: systembartint: 1.0.4’ The first one we are more familiar with, not to say (really don’t know it, an mo method, find Baidu or aunt, ha ha); The second one is mainly an application of the immersive status bar. The color of the status bar also changes, which makes it more comfortable to look at, right? The version number will only be updated according to the official version. The github code address of Maven’s central repository is the github code address of Maven’s central repository

2, the code part of the code implementation, with things very simple.

1. Use of layout files, i.e. ViewPager. The XML code is as follows:

 

   

    
    
    
    
    
    
    

Copy the code

The annotation part is a customized indicator, which can be a number or a small circle.

2, The resource file code I wrote in the arrays.xml file:
I felt good about blogging for the first time, @mipmap/ splash_IV_first @mipmap/ splash_IV_second @mipmap/splash_iv_third @mipmap/splash_iv_forth @color/light_green_500 @color/amber_500 @color/red_400 @color/blue_500Copy the code

The first is some text for each page; The second is some pictures, ICONS; The third is the background color. These are all required for each page of the ViewPager, and you can modify them according to your own needs. (Of course, the demo can also do without this content, just need a solid color background just to look good, ha ha).

The ViewPager layout is as follows:
      
                  
                  
                           
                          Copy the code
                
        Copy the code

The open button can be hidden first and displayed on the last page.

4. Main implementation code:

The basics of how to create a page, how Mainfest references an activity, and how to reference a control are left out. 1, First get the root layout control to set the background color:

 mRootLayout = (RelativeLayout)findViewById(R.id.rl_root);Copy the code

2, Then the use of ViewPager, need to set it to the PagerAdapter:

private class IntroPager extends PagerAdapter { private String[] mDescs; private TypedArray mIcons; public IntroPager(int icoImage, int des) { mDescs = getResources().getStringArray(des); mIcons = getResources().obtainTypedArray(icoImage); } @Override public int getCount() { return mIcons.length(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { View itemLayout = getLayoutInflater().inflate(R.layout.layout_app_intro, container, false); ImageView mImage = (ImageView)itemLayout.findViewById(R.id.iv_img); TextView mTextView = (TextView)itemLayout.findViewById(R.id.tv_desc); Button mButton = (Button)itemLayout.findViewById(R.id.btn_launch); mImage.setImageResource(mIcons.getResourceId(position, 0)); mTextView.setText(mDescs[position]); if (position == getCount() - 1) { mButton.setVisibility(View.VISIBLE); } else { mButton.setVisibility(View.GONE); } container.addView(itemLayout); return itemLayout; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View)object); }}Copy the code

The code, not to mention, is relatively simple. The key is a reference to a resource file of the constructor. 3, ViewPager add slide listener: slide listener code is the focus of this time, previously used setOnPageChangeListener, but has been abolished, use addOnPageChangeListener, and then implement inside the onPageScrolled method. As follows:

mViewPager.addOnPageChangeListener(new     ViewPager.OnPageChangeListener()
    {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
        {
            int colorBg[] = getResources().getIntArray(R.array.splash_bg);
            ColorShades shades = new ColorShades();
            shades.setFromColor(colorBg[position % colorBg.length])
                .setToColor(colorBg[(position + 1) % colorBg.length])
                .setShade(positionOffset);
            mRootLayout.setBackgroundColor(shades.generate());
            applySelectedColor(shades.generate());
        }
        @Override
        public void onPageSelected(int position)
        {   
        }
        @Override
        public void onPageScrollStateChanged(int state)
        {
        }
    });Copy the code

As you can see, the key is the combination of ColorShades and onPageScrolled inside a parameter. (1) First look at the onPageScrolled parameters: position: on the first and last page, slide to the next page, position is the current page position; Slide to previous page, position is current page -1. PositionOffset: slide to next page, change on range [0,1]; slide to previous page, change on range: (1,0]. PositionOffsetPixels: This is similar to positionOffset: slide to the next page and change on the [0, width] interval; slide to the previous page and change on the (0, width) interval. On the first page: slide to the previous page position=0, otherwise basically 0; Last page slide to Next Page Position is the current page position and the other two parameters are 0. So positionOffset is a good control parameter for gradients and scales; PositionOffsetPixels can be used as a control parameter for translation, etc. PositionOffset can then be used to change the background color to a gradient when sliding. (2) ColorShades: it mainly realizes the change from which color to which color, and uses positionOffset to control the gradient of color, and returns a new color value composed of RGB. We only need to set this color value. The code is as follows:

/** * Source from : https://gist.github.com/cooltechworks/4f37021b1216f773daf8 * Color shades will provide all the intermediate colors Between two colors. It just requires a decimal value between * 0.0 to 1.0 * and It provides the exact shade combination of the two color with this shade value. * Textual explanation : * * White LtGray Gray DkGray Black * 0 0.25 0.5 0.75 1 * Given two colors as White and Black,and shade * as 0 gives White * as 0.25 gives Light gray * as 0.5 gives gray * as 0.75 gives Dark gray * as 1 gives Black. */ public class ColorShades { private int mFromColor; private int mToColor; private float mShade; public ColorShades setFromColor(int fromColor) { this.mFromColor = fromColor; return this; } public ColorShades setToColor(int toColor) { this.mToColor = toColor; return this; } public ColorShades setFromColor(String fromColor) { this.mFromColor = Color.parseColor(fromColor); return this; } public ColorShades setToColor(String toColor) { this.mToColor = Color.parseColor(toColor); return this; } public ColorShades forLightShade(int color) { setFromColor(Color.WHITE); setToColor(color); return this; } public ColorShades forDarkShare(int color) { setFromColor(color); setToColor(Color.BLACK); return this; } public ColorShades setShade(float shade) { this.mShade = shade; return this; } /** * Generates the shade for the given color. * * @return the int value of the shade. */ public int generate() { int fromR = Color.red(mFromColor); int fromG = Color.green(mFromColor); int fromB = Color.blue(mFromColor); int toR = Color.red(mToColor); int toG = Color.green(mToColor); int toB = Color.blue(mToColor); int diffR = toR - fromR; int diffG = toG - fromG; int diffB = toB - fromB; int red = fromR + (int)((diffR * mShade)); int green = fromG + (int)((diffG * mShade)); int blue = fromB + (int)((diffB * mShade)); return Color.rgb(red, green, blue); } /** * Assumes the from and to color are inverted before generating the shade. * @return the int value of the inverted shade. */ public int generateInverted() { int fromR = Color.red(mFromColor); int fromG = Color.green(mFromColor); int fromB = Color.blue(mFromColor); int toR = Color.red(mToColor); int toG = Color.green(mToColor); int toB = Color.blue(mToColor); int diffR = toR - fromR; int diffG = toG - fromG; int diffB = toB - fromB; int red = toR - (int)((diffR * mShade)); int green = toG - (int)((diffG * mShade)); int blue = toB - (int)((diffB * mShade)); return Color.rgb(red, green, blue); } /** * Gets the String equivalent of the generated shade * @return String value of the shade */ public String generateInvertedString() { return String.format("#%06X", 0xFFFFFF & generateInverted()); } /** * Gets the inverted String equivalent of the generated shade * @return String value of the shade */ public String generateString() { return String.format("#%06X", 0xFFFFFF & generate()); }}Copy the code

This is somebody else made the wheel, the source address is also in the comments inside. Small friends can go to see what Daniel wrote. Then set the background color:

mRootLayout.setBackgroundColor(shades.generate());

This basically completes the function of sliding gradient background color, but it doesn’t look good, if the status bar color also changes, the entire screen is one color, it looks better. Then we use the second dependency package to set the status bar color. How to use it, I can refer to the author code address given earlier, and then I will also post my implementation of the code. Mainly in the onCreate method:

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); If (build.version.sdk_int >= build.version_codes.kitkat) {// Transparent status bar getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); / / transparent navigation getWindow (). AddFlags (WindowManager. LayoutParams. FLAG_TRANSLUCENT_NAVIGATION); } setContentView(R.layout.activity_app_intro); mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setNavigationBarTintEnabled(true); applySelectedColor(R.color.light_green_500); // Set the color of the first page init(); } // Set the status bar color, in onPageScrolled set the same value as the background color. private void applySelectedColor(int color) { mTintManager.setTintColor(color); }Copy the code

Okay, so that’s basically what the code looks like, and then what it looks like is what it looks like. Write an article for the first time, hope everybody gives valuable suggestion, as well as improper place please make correct, have better realization method, everybody also can contact ah, hey hey, everybody study together. Thank you! Mua!!! Oh, by the way, over 5.0 operating effects!