如何根据项目的总高度设置listview高度?

时间:2015-02-26 14:22:38

标签: android android-layout listview android-listview android-view

我已经像这样设置了listview高度,函数工作正常,但是,当listview中的某个项目开头是VIEW.GONE而后面的VISIBLE时,视图更新因此元素的后半部分超出了屏幕而无法显示。如何解决问题?

1。这是根据项目总高度设置listview高度的代码

 public static void updateListViewHeight(ListView myListView) {
        ListAdapter myListAdapter = myListView.getAdapter();
        if (myListAdapter == null) {
            return;
        }
        // get listview height
        int totalHeight = 0;
        int adapterCount = myListAdapter.getCount();
        for (int size = 0; size < adapterCount; size++) {
            View listItem = myListAdapter.getView(size, null, myListView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        // Change Height of ListView
        ViewGroup.LayoutParams params = myListView.getLayoutParams();
        params.height = totalHeight + (myListView.getDividerHeight() * (adapterCount - 1));
        myListView.setLayoutParams(params);
     }

2。以及初始化listview 的方法,除了有隐藏元素并希望稍后在listview中显示之外,它的工作正常

private void initCommentData() {
    customAdapter = new CommentAdapter(ctx, R.layout.item_list_detail, comment_list);
    listView.setAdapter(customAdapter);
    Utility.updateListViewHeight(listView);
    comment.requestFocus();
    scroll.smoothScrollTo(0, 0);
    customAdapter.notifyDataSetChanged();
}

第3。这就是我隐藏元素的方式

reply.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(comment_bar.isShown()){
                                comment_bar.setVisibility(View.GONE);
                                reply.setText(getResources().getString(R.string.reply) + " +");
                            }else{
                                comment_bar.setVisibility(View.VISIBLE);
                                reply.setText(getResources().getString(R.string.reply) + " -");
                            }

                            updateListViewHeight(listView);
                        }
                    });

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

调用setVisibility并不意味着该视图会立即改变大小。布局过程必须在调用updateListViewHeight方法之前进行。在这个例子中我使用了handler,另一个解决方案是添加布局监听器。

        reply.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if(comment_bar.isShown()){
                comment_bar.setVisibility(View.GONE);
                reply.setText(getResources().getString(R.string.reply) + " +");
            }else{
                comment_bar.setVisibility(View.VISIBLE);
                reply.setText(getResources().getString(R.string.reply) + " -");
            }
            comment_bar.postDelayed(new Runnable() {
                updateListViewHeight(listView);
            }, 500);
        }
    });