如何在运行时计算listview项目高度并在android中设置所有具有相同高度的项目?

时间:2012-03-21 15:20:45

标签: android listview listviewitem

在我的应用程序中,我有一个列表视图,我正在将Web视图扩展到列表视图中。我能够将数据和图像加载到列表视图项中。问题是由于内容不同,列表项的高度不同。我想让所有列表项具有相同的高度

如何计算具有最大数据的列表项的高度,并将该高度设置为列表中其余列表项的高度。

我该怎么做...我对此毫无头绪。如果第10项具有最大高度,我想将该高度应用于其余部分。帮助我实现这一点,并感谢您的支持

<?xml version="1.0" encoding="utf-8"?>

<WebView
    android:id="@+id/wv1" 
    android:layout_width="fill_parent" android:paddingRight="20dp"
    android:layout_height="wrap_content" />

1 个答案:

答案 0 :(得分:0)

有一系列标志,比如说

boolean[] flags=new boolean[szieOfList];

将此数组填充为false;

在你的活动或适配器中有一个变量max height,比如max,在onCreate方法中用0初始化它,现在在你正在膨胀xml的getView方法中,写下面的代码:

LayoutInflater layoutInflater = (LayoutInflater) getActivity()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= (WebView) layoutInflater
            .inflate(R.layout.web_view, null);
if(flag[position])
{
      LayoutParams params = view.getLayoutParams();
              params.height = max;
              view.setLayoutParams(params);
}     
ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        //in here, place the code that requires you to know the dimensions.

         flag[position]=true;
         int height= view.getHeight();
         if(max<height)
         {
              max=height;
              notifyDataSetInvalidated();
         }
          else
         {
               LayoutParams params = view.getLayoutParams();
              params.height = max;
              view.setLayoutParams(params);
         }
         //this will be called as the layout is finished, prior to displaying.
    }
}