Inserting a ListView in ScrollView is a big problem. One of the problems is that the height of the ListView is very difficult to calculate, the output is often very bad, let us look at the problem.
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:background= "#FFE1FF"android:orientation= "Vertical" > <ScrollView android:layout_width= "Match_parent"Android:layout_height= "Match_parent" > <LinearLayout android:layout_width= "Match_parent"Android:layout_height= "Match_parent" > <ListView Android:id= "@+id/listview1"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:fadingedge= "Vertical"Android:fadingedgelength= "5DP"/> </LinearLayout> </ScrollView> </LinearLayout>
You can see that the columns of text in the ListView can only show one line, the interface is bad, how to solve the height problem, let's re-design.
Public classMainactivityextendsActivity {PrivateListView ListView; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); ListView=(ListView) Findviewbyid (R.ID.LISTVIEW1); String[] Adapterdata=NewString[] {"Afghanistan", "Albania",... ... "Bosnia"}; Listview.setadapter (NewArrayadapter<string> ( This, Android. R.layout.simple_list_item_1,adapterdata)); Setlistviewheightbasedonchildren (ListView); } Public voidSetlistviewheightbasedonchildren (ListView listview) {//Get the adapter of the ListViewListAdapter ListAdapter =Listview.getadapter (); if(ListAdapter = =NULL) { return; } intTotalheight = 0; for(inti = 0, Len = Listadapter.getcount (); i < Len; i++) { //Listadapter.getcount () returns the numbers of the itemsView ListItem = Listadapter.getview (i,NULL, ListView); //the design of the operator viewListitem.measure (0, 0); //The total height of all the childrenTotalheight + =listitem.getmeasuredheight (); } viewgroup.layoutparams params=Listview.getlayoutparams (); Params.height= totalheight+ (Listview.getdividerheight () * (Listadapter.getcount ()-1)); //listview.getdividerheight () The height of the separator occupied by the child//Params.height finally get the full display of the entire ListView required heightlistview.setlayoutparams (params); }}
Wirelessly tutorial (4): The height of the ScrollView and the ListView problem