The recent project has a requirement that requires a nested display of multiple layers of sliding controls, the demo effect is as follows, the demo is at the end
I look like a very simple ah, not just a ScrollView + Viewpager + listview, I began to feel the same way, also used in this manner, the result is always and the effect is not right. Here are a few questions to summarize:
- When two or more sliding controls are nested, if Layout_height is using wrap_content, the height of the inner slide control is not calculated correctly, causing the internal slide control to always be the height of 0, unless you set it to a fixed value, such as 300DP.
- Two sliding controls nested in the same sliding direction invalidate the sliding event of one of the controls.
- If ScrollView is used as the outermost sliding control, there will be an inexplicable shift bug, which is found to be a scrolly exception change through the log, but is not valid through the Scrollto method.
- When Viewpager nesting a ListView, the default Viewpager height is the highest of all the ListView, so there will be a large chunk of padding at the bottom of the other ListView.
The above is my summary of the several issues that have occurred, perhaps your question is the above, perhaps some of the problems have not been summed up, but I believe this blog will be helpful to you.Well, let's start by listing a few things that we need to solve.
- Just now, using ScrollView as the outermost slide control to nest other sliding controls, there is an inexplicable displacement bug, so you should change a sliding control as the outermost container.
- Two sliding controls are nested, the height of the inner slide control will be 0 by default, unless you set the value setting, if you do not want to set the value, then you need to customize the slide control, manually calculate the slide control.
- Viewpager nested listview There is a large gap in the bottom of the ListView with less data, so here we also need to customize the Viewpager to dynamically calculate the height of the current listview.
- The ListView is a sub-slide control of the top-level slide control Viewpager, and the height default is also 0, where we also need to customize the height of the ListView calculation.
First we solve the first problem,that is, what controls are used instead of ScrollView as top-level sliding controls. The answer is the ListView,Some small partners do not understand, the ListView as the top-level control? No, how do you do that? To tell the truth, I used the ListView only for one reason: The ListView will not have a bug of displacement. Next I'll use a picture to explain.
As you can see from the graph, the top-level listview contains two parts, one header, some other controls and the Indicatorview navigation bar, and then the ListView item,The point is that the item has only one number, that is, take viewpager as item. Then Viewpager nested inside the fragment as a fragment of the display, each fragment also contains a ListView as a data list display. Here's the code for the top-most sliding control: first, the activity's layout file: Actvity_main.xml
<?xml version= "1.0" encoding= "Utf-8"? ><listview xmlns:android= "http://schemas.android.com/apk/res/ Android " android:id=" @+id/listview " android:layout_width=" match_parent " android:layout_height=" Match_parent " android:cachecolorhint=" @android: color/transparent " android:divider=" @null " android: dividerheight= "0DP" android:listselector= "@android: Color/transparent"/>
Very simple, just a ListView. Then the Mainactiivity.class:
public class Mainactivity extends fragmentactivity {private Tabpageindicator indicator; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); ListView ListView = (ListView) Findviewbyid (R.id.listview); View Header = View.inflate (this, r.layout.header, null); Indicator = (tabpageindicator) Header.findviewbyid (r.id.indicator); Listview.addheaderview (header); Listview.setadapter (New Customadapter (this)); } public class Customadapter extends baseadapter{private view view; Private Wrapcontentviewpager Viewpager; Public Customadapter (Context context) {view = View.inflate (context, r.layout.item_main, null); Viewpager = (Wrapcontentviewpager) View.findviewbyid (R.id.viewpager); Viewpager.setadapter (New Listfragmentadapter (Viewpager, Getsupportfragmentmanager ())); Indicator.setviewpAger (Viewpager); Viewpager.setonpagechangelistener (New Viewpager.onpagechangelistener () {@Override public vo ID onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {} @Overrid e public void onpageselected (int position) {viewpager.resetheight (position); Indicator.setcurrentitem (position); } @Override public void onpagescrollstatechanged (int state) {}}) ; Viewpager.resetheight (0); } @Override public int getcount () {return 1; } @Override public Object getItem (int position) {return null; } @Override public long getitemid (int position) {return 0; } @Override public View getView (int position, view Convertview, ViewGroup parent) {RetuRN view; } }}
In mainactivity two main things: 1, introduced a separate layout file as a ListView Header2, from the header to instantiate the Viewpager navigation control Indicator3, Sets the custom adapter for the ListView, causes GetCount to return 1, displays only one Item4, instantiates the custom Viewpager in the unique item, and sets the adapter adapter
The first is the header layout file: Header.xml
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" wrap_content "android:orientation=" vertical " > <textview android:layout_width= "match_parent" android:layout_height= "80DP" Android:grav ity= "center" android:background= "@android: Color/holo_red_light" android:text= "Hello world!"/> <tex TView android:layout_width= "match_parent" android:layout_height= "80DP" android:gravity= "center" Android:background= "@android: Color/holo_blue_light" android:text= "Hello world!"/> <textview Android Oid:layout_width= "Match_parent" android:layout_height= "80DP" android:gravity= "center" Android:backgro Und= "@android: Color/holo_orange_light" android:text= "Hello world!"/> <textview Android:layout_widt H= "Match_parent" Android:layout_height= "80DP" android:gravity= "center" android:background= "@android: Color/holo_green_light" Andro id:text= "Hello world!"/> <cc.wxf.androiddemo.indicator.tabpageindicator android:id= "@+id/indicator" Android:layout_width= "Match_parent" android:layout_height= "Wrap_content"/></linearlayout>
The header here contains only a few TextView as a demo, and then contains the navigation control indicator. Then the ListView is the only item of the layout file Item_main.xml:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" match_parent " android:layout_height=" wrap_content "> < Cc.wxf.androiddemo.WrapContentViewPager android:id= "@+id/viewpager" android:layout_width= "match_parent " android:layout_height=" Wrap_content "/></linearlayout>
The display of the first layer of control is over, the key is the second layer of the display problem, Viewpager + Fragment + ListView.As already said, Viewpager as a sliding control, nested in the ListView, if you do not do a special operation, the height is always 0, then how to customize it?What we need to do with this viewpager:
- Need to know the height of all child controls
- The Onmeasure method needs to be overridden so that the height of the currently displayed child control is Viewpager
- You need to dynamically change the height of the Viewpager to the height of the current child control when the page changes
First give the source code for the definition Viewpager: Wrapcontentviewpager.class
Package Cc.wxf.androiddemo;import Android.content.context;import Android.support.v4.view.viewpager;import Android.util.attributeset;import Android.widget.linearlayout;import Java.util.hashmap;import Java.util.Map;public Class Wrapcontentviewpager extends Viewpager {private Map<integer, integer> maps = new Hashmap<integer, Integ Er> (); private int current; Public Wrapcontentviewpager (context context, AttributeSet Attrs) {Super (context, attrs); } public Wrapcontentviewpager (context context) {super (context); } @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {int height = 0; if (Maps.size () > Current) {height = Maps.get (current + 1); } Heightmeasurespec = Measurespec.makemeasurespec (height, measurespec.exactly); Super.onmeasure (Widthmeasurespec, Heightmeasurespec); } public void Resetheight (int.) {this.current = current; if (maps.sizE () > current) {linearlayout.layoutparams Layoutparams = (linearlayout.layoutparams) getlayoutparams (); if (Layoutparams = = null) {layoutparams = new Linearlayout.layoutparams (LinearLayout.LayoutParams.MA Tch_parent, Maps.get (current + 1)); }else{layoutparams.height = maps.get (current + 1); } setlayoutparams (Layoutparams); }} public void calculate (int type, int height) {maps.put (type, height); }}
The principle is very simple, first give a map of the data structure, the location of all the child control and the corresponding height of the mapping table, and then give a current field, representing the currently displayed index of the page. In the Onmeasure method, dynamically calculates the height of the current child control based on the current display index, and assigns the value to Viewpager. In the Resetheight method, the index of the current child control is changed and the height of the current Viewpager is changed dynamically. In the Calculate method, place the position and height of the child control in the mapping table,The calculate method is called in a custom ListView., the reason behind the article will be understood.Then there is the code for the Viewpager corresponding Fragmentpageadapter:
Package Cc.wxf.androiddemo;import Android.support.v4.app.fragment;import Android.support.v4.app.FragmentManager; Import Android.support.v4.app.fragmentpageradapter;import Java.util.arraylist;import Java.util.List;import cc.wxf.androiddemo.indicator.iconpageradapter;/** * Created by CCWXF on 2016/6/17. */public class Listfragmentadapter extends Fragmentpageradapter implements iconpageradapter{private LIST<LISTFRAGM ent> fragments = new arraylist<listfragment> (); private static final string[] CONTENT = new string[] {"Calendar", "Camera", "Alarms", "location"}; Public Listfragmentadapter (Wrapcontentviewpager Viewpager, Fragmentmanager FM) {super (FM); Fragments.add (New Listfragment (Viewpager, 1)); Fragments.add (New Listfragment (Viewpager, 2)); Fragments.add (New Listfragment (Viewpager, 3)); } @Override public Fragment getItem (int position) {return fragments.get (position); } @Override public int geticonresid (int indEx) {return r.drawable.selector_indicator; } @Override public charsequence getpagetitle (int position) {return content[position% Content.length].touppe Rcase (); } @Override public int getcount () {return fragments.size (); }}
Here the adapter implements the Iconpageradapter interface just to be compatible with the use of the navigation control indicator,for the use of navigation control indicator, refer to the GitHub Open Source Library: ViewpagerindicatorThen there is the code for Listfragment:
Package Cc.wxf.androiddemo;import Android.annotation.suppresslint;import Android.os.bundle;import Android.support.annotation.nullable;import Android.support.v4.app.fragment;import Android.view.LayoutInflater; Import Android.view.view;import Android.view.viewgroup;import Android.widget.arrayadapter;import Java.util.arraylist;import java.util.list;/** * Created by CCWXF on 2016/6/17. */public class Listfragment extends Fragment {private Wrapcontentviewpager viewpager; private int type; Public listfragment () {} @SuppressLint ("Validfragment") public listfragment (Wrapcontentviewpager viewpager, int Type) {This.viewpager = Viewpager; This.type = type; } @Override Public View oncreateview (Layoutinflater inflater, @Nullable viewgroup container, @Nullable Bundle Savedi Nstancestate) {View view = Inflater.inflate (R.layout.fragment_item, NULL); Wrapcontentlistview ListView = (wrapcontentlistview) View.findviewbyid (R.id.listview); List<string> data = new arraylist<string> (); for (int i = 0; i < type * 5; i++) {Data.add ("AAA"); } listview.setadapter (New Arrayadapter<string> (Getactivity (), Android. R.layout.simple_list_item_1, data)); Viewpager.calculate (Type, listview.getrealheight ()); return view; }}
Here the listfragment just made a custom ListView for an initialization.It is important to note that the Viewpager.calculate method in the Oncreateview method, where the height of the corresponding child control ListView is passed back to the Viewpager, and the code must be executed after the Setadapter, to ask why? Don't worry, we have a fragment_item.xml layout file is not published, in fact, super simple.
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:orientation=" vertical "android:layout_width=" match_parent " android:layout_height=" Match_parent "> <cc.wxf.androiddemo.wrapcontentlistview android:id=" @+id/listview " android: Layout_width= "Match_parent" android:layout_height= "match_parent" android:cachecolorhint= "@android: Color/transparent " android:divider=" @android: Color/darker_gray " android:dividerheight=" @dimen/divider " android:listselector= "@android: Color/transparent"/></linearlayout>
is not super simple. In fact, it contains a custom ListView, then the most important work comes, this custom ListView how to write.
Package Cc.wxf.androiddemo;import Android.content.context;import Android.util.attributeset;import Android.view.view;import android.widget.listadapter;import android.widget.listview;/** * Created by CCWXF on 2016/6/ */public class Wrapcontentlistview extends ListView {private int height; Public Wrapcontentlistview (Context context) {super (context); } public Wrapcontentlistview (context context, AttributeSet Attrs) {Super (context, attrs); } public Wrapcontentlistview (context context, AttributeSet attrs, int defstyle) {Super (context, Attrs, Defstyle ); } @Override public void Setadapter (ListAdapter adapter) {Super.setadapter (adapter); View item = adapter.getview (0, NULL, NULL); Item.measure (Measurespec.makemeasurespec (0, measurespec.unspecified), Measurespec.makemeasurespec (0, measurespec.unspecified)); int itemheight = Item.getmeasuredheight (); int count = Adapter.getcount (); Height = ItemheighT * count + getresources (). Getdimensionpixelsize (R.dimen.divider) * count; Measure (Measurespec.makemeasurespec (0, measurespec.unspecified), height); } public int Getrealheight () {return height; } @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (widthmeas Urespec, Measurespec.makemeasurespec (height, measurespec.exactly)); }}
After Setadapter, the dynamic measure the height of the first item and accumulates the height of the count item and the height of the divider (do not underestimate the height of this divider, if not added will result in the last item cannot be displayed),There is also a limitation: the height of each item in the top-most ListView must be consistent, meaning the item style can only be the same. Otherwise there is no way to calculate, some small partners will ask, then I do not put each item is measure, you think carefully if there is a count of 100?
And then the Getrealheight method, which is to return the calculated height,Now you know why this method has to be called after the Setadapter method .。 In the Onmeasure method, the calculated height is set to my height directly. Here is a good question to ask the little friend to ask:will the height here be equal to 0? The small partner who raised this question had better think about the order in which Setadapter and Onmeasure are called, in the order in which Oncreateview and onmeasure are called in this article, the clever little companion was so awakened by me, was it immediately clear?
At the end of the demo:Click I download demo
Conflict resolution for nested sliding controls on Android and Viewpager to fit the current child control height without leaving blank