名人名言:忏悔是对信徒非常有益但主要对罗马教会的教士非常方便的发明。由于这个方法,他们能知道所有家庭秘密,能引起夫妻口角,如果需要的话,也可激起宗教叛乱。在忏悔不风行了的国家,教会失去了一个施加影响的强大工具。——霍尔巴赫
运行成果,OK题目搞定,打完收工!
在开辟的过程傍边,因为屏幕的大小的限制,我们经常须要应用滑动的体式格式,来显示更多的内容。在比来的工作中,碰见一个需求,须要将ListView嵌套到ScrollView中显示。于是乎有了如下布局:
- <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>
运行法度,如下成果,无论你如何调剂layout_width,layout_height属性,ListView列表只显示一列!
![](http://pic-server2.byywee.com/M0/S906/906408-0.jpg)
在查阅的各类文档和材料后,发明在ScrollView中嵌套ListView空间,无确的策画ListView的大小,故可以经由过程代码,按照当前的ListView的列表项策画列表的尺寸。实现代码如下:
- public class MainActivity extends Activity {
- private ListView listView;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- listView = (ListView) findViewById(R.id.listView1);
- String[] adapterData = new String[] { "Afghanistan", "Albania",… … "Bosnia"};
- listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,adapterData));
- setListViewHeightBasedOnChildren(listView);
- }
- public void setListViewHeightBasedOnChildren(ListView listView) {
- // 获取ListView对应的Adapter
- ListAdapter listAdapter = listView.getAdapter();
- if (listAdapter == null) {
- return;
- }
-
- int totalHeight = 0;
- for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
- // listAdapter.getCount()返回数据项的数量
- View listItem = listAdapter.getView(i, null, listView);
- // 策画子项View 的宽高
- listItem.measure(0, 0);
- // 统计所有子项的总高度
- totalHeight += listItem.getMeasuredHeight();
- }
-
- ViewGroup.LayoutParams params = listView.getLayoutParams();
- params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
- // listView.getDividerHeight()获取子项间分隔符占用的高度
- // params.height最后获得全部ListView完全显示须要的高度
- listView.setLayoutParams(params);
- }
- }
运行成果,OK题目搞定,打完收工!