Android Design supports TabLayout library to create a Tab effect similar To Netease News (37)

Source: Internet
Author: User

Android Design supports TabLayout library to create a Tab effect similar To Netease News (37)

 

(1). Preface:

During the development of the 36Kr client, because there are many types of news articles on their website, I am still going to simulate the News Tab and page sliding effect on the main interface of Netease news APP. There are many ways to achieve the effect of the top Tab, such as using TabPageIndicator In the open-source project ViewPagerIndicator. But today we will not talk about ViewPagerIndicator. Let's talk about the TabLayout component released by Google this year. At the Google conference in 2015, the new Android Support Design Library released by google also contains several new controls, so TabLayout is one of them. Using this component, we can easily implement the TabPageIndicator effect. It is officially compatible with many versions and can unify the Material Design effect. However, the source code of TabLayout shows that the component is also inherited from HorizontalScrollView.

Use HorizontalScrollView to create a Netease-like tab effect. Click to enter...

The code in this example has been uploaded to the following project. You are welcome to go to star and fork.

 

(2). Usage:

. My projects are developed using Android Studio. Therefore, we must first introduce the dependency library of TabLayout, as shown below:

 

compile'com.android.support:design:23.1.1'compile'com.android.support:appcompat-v7:23.1.1'

 

(3). effect implementation:

We now need to follow the Tab switch of Netease News (36Kr client) and the switch effect of the Bottom News Page. The TabLayout component is used for Tab label implementation, and Fragment + ViewPager + FragmentStatePagerAdapter is used for page switching at the bottom.

[Note]: The Activity that carries Fragment will not be explained here. For details, refer to the previous article and the code of this project. Let's start with Fragment.

3. 1. First, we need to create a layout file for Fragment as follows:

 

 
     
          
 

 

The layout mainly consists of two controls: the first is the TableLayout component, which is the container of the Tab label, and the second is the ViewPager component which is mainly used to display several Fragment for page switching. You should have noticed the following three custom attributes in the TabLayout component:

 

App: tabIndicatorColor = @ color/white // scroll underline color app: tabSelectedTextColor = @ color/gray // The text color app after the tab is selected: tabTextColor = @ color/white // default text color of the tab

 

These three custom attributes are provided by TabLayout. We can modify the title Color and indicator color at will. In addition, we also provide the following style settings:

  • TabMaxWidth
  • TabIndicatorColor
  • TabIndicatorHeight
  • TabPaddingStart
  • TabPaddingEnd
  • TabBackground
  • TabTextAppearance
  • TabSelectedTextColor

    3. 2. next is the CNKFixedPagerAdapter, which is the custom adapter of ViewPager. Each item in ViewPager is implemented using Fragment, so the set of pages that get Fragment is passed in, an array of Tab display titles is also defined.

     

    Package com. chinaztt. fda. adapter; import android. support. v4.app. fragment; import android. support. v4.app. fragmentManager; import android. support. v4.app. fragmentStatePagerAdapter; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widget. imageView; import android. widget. textView; import com. chinaztt. fda. application. FDApplication; import com. chinaztt. fda. ui. r; import java. util. list;/*** current class annotation: Fragment, custom adapter of Viewpager * Project name: FastDev4Android * package name: com. chinaztt. fda. adapter * Author: Jiang Qing on 15/12/2 * mailbox: jiangqqlmj@163.com * QQ: 781931404 * company: jiangsu Zhongtian Technology Software Technology Co., Ltd. */public class CNKFixedPagerAdapter extends FragmentStatePagerAdapter {private String [] titles; private LayoutInflater mInflater; public void setTitles (String [] titles) {this. titles = titles;} private List
       
        
    Fragments; public CNKFixedPagerAdapter (FragmentManager fm) {super (fm) ;}@ Override public Fragment getItem (int position) {return this. fragments. get (position) ;}@ Override public int getCount () {return this. fragments. size () ;}@ Override public Object instantiateItem (ViewGroup container, int position) {Fragment fragment = null; try {fragment = (Fragment) super. instantiateItem (container, position);} catch (Exception e) {}return fragment;} @ Override public void destroyItem (ViewGroupcontainer, int position, Object object Object) {}// this method is used to display the name @ Override public CharSequence getPageTitle (intposition) {return titles [position % titles. length];} public List
        
         
    GetFragments () {return fragments;} public void setFragments (List
         
          
    Fragments) {this. fragments = fragments ;}}
         
        
       

     

    In this Adapter, We overwrite the getPageTitle () method to display the Tab title.

    3. The following figure shows the specific Fragment (TabInfoFragment). In this Fragment, We initialize ViewPager, TabLayout, user-defined adapter, Fragment page, and the displayed Tab title.

    Finally, we bound the adapter to ViewPager, and TabLayout to ViewPager.

     

    Public class TabInfoFragment extends Fragment {private String [] titles = new String [] {all, krypton TV, O2O, new hardware, Fun !!, Enterprise Service, Fit & Health, online education, internet finance, large companies, columns, new products}; private View mView; private TabLayout tab_layout; private ViewPager info_viewpager; private List
       
        
    Fragments; private CNKFixedPagerAdapter mPagerAdater; @ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {if (mView = null) {mView = inflater. inflate (R. layout. tab_info_fragment_layout, container, false); initViews (); initValidata ();} return mView;} private void initViews () {tab_layout = (TabLayout) mView. findViewById (R. id. tab_layout); info_viewpager = (ViewPager) mView. findViewById (R.id.info _ viewpager);} private void initValidata () {fragments = new ArrayList <> (); for (int I = 0; I <12; I ++) {OneFragment oneFragment = new OneFragment (); Bundle bundle = new Bundle (); bundle. putString (extra, titles [I]); oneFragment. setArguments (bundle); fragments. add (oneFragment);} // create the ViewPager custom adapter for Fragment mPagerAdater = new CNKFixedPagerAdapter (getChildFragmentManager (); // set the title mPagerAdater. setTitles (titles); // set the page Fragment mPagerAdater to be slide. setFragments (fragments); info_viewpager.setAdapter (mPagerAdater); Aggregate (info_viewpager); // set Tablayout // set TabLayout mode-tab_layout.setTabMode (TabLayout. MODE_SCROLLABLE );}}
       

     

    I believe you have seen the last sentence of this Code:

     

     tab_layout.setTabMode(TabLayout.MODE_SCROLLABLE);

     

    This is used to set the Tablayout mode. In addition to the above default mode, there is also a mode as follows:

     

     tab_layout.setTabMode(TabLayout.MODE_FIXED);

     

    The differences between the two are as follows. If the number of tabs is relatively large, the Tab label can be Slide left and right.

    3. 4. The running effect is as follows:

    (4) Tab upgrade:

    The above effect is that the basic version directly displays the title of the Tab, and sometimes it does not meet our requirements. Now we can transform it so that the Tab created by TabLayout can display both the icon and the text title information. This is mainly implemented using the following methods of Tab:

     

    Tab. setCustomView (view); custom Layout added by tab

     

    4. 1. First, we need to define a layout file for each Item of the Tab Item:

     

       
           
            
         
        
       

     

    This layout file is simple, with the up and down layout icons and titles

    4. 2. then we need to modify the following in CNKFixedPagerAdapter: Previously we used to rewrite the public CharSequence getPageTitle (int position) method to display the title. Now we need to delete or comment out this method, then a new getTabView () method is added to create the layout of the Tab Item in real time and bind the data:

     

    /*** Add the getTabView method to customize the Layout View of the Tab * @ param position * @ return */public View getTabView (int position) {mInflater = LayoutInflater. from (FDApplication. getInstance (); Viewview = mInflater. inflate (R. layout. tab_item_layout, null); TextView TV = (TextView) view. findViewById (R. id. textView); TV. setText (titles [position]); ImageView img = (ImageView) view. findViewById (R. id. imageView); img. setImageResource (R. mipmap. ic_launcher); return view ;}

     

    4. 3. after completing these steps, you can set each Tab in Tablayout in the main Fragment (TabInfoFragment) as follows: Get each Tab, and then set a custom layout for the Tab to call the tab. setCustomView () method.

     

    // Set the custom Tab -- add the demo for (int I = 0; I <12; I ++) {TabLayout. tab tab = tab_layout.getTabAt (I); tab. setCustomView (mPagerAdater. getTabView (I ));}

     

    4. The running result is as follows:

    (5). Conclusion

    Today, we use the TabLayout component of the Android Design support library to achieve page slide and top Tab effects modeled on the homepage of Netease news client. I hope it will be helpful for you to use the previous method. Although this effect can be displayed, the technology is developing. keep up with the trend of the times ~ Hey.

    Because there are many instance codes, the key core code has been posted. However, all the code commented on by the instance has been uploaded to the Github project. At the same time, you are welcome to go to The Github site to clone or fork the entire open-source quick development framework project ~

     

     

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.