码迷,mamicode.com
首页 > 移动开发 > 详细

安卓中級教程(4):ScrollView與ListView之間的高度問題

时间:2015-05-16 17:56:18      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

在scrollView中加插ListView是一個大難題。其中一個難題是Listview的高度難以計算,輸出效果往往強差人意,就讓我們看看當中的問題 。

 

<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> 

技术分享

大家可以看到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);   }}
    

 

技术分享

 

安卓中級教程(4):ScrollView與ListView之間的高度問題

标签:

原文地址:http://www.cnblogs.com/kanchihong/p/4508150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!