How to calculate the listview Item height at run time and set all items with same height in android?

别说谁变了你拦得住时间么 提交于 2019-12-11 12:17:02

问题


In my application i have a list view and i am inflating a web view into the list view. I am able to load data and images into the list view item. The problem is the list items are not of same height due to different contents. I want to make all list items having same height

How to calculate the height of the list item that has the maximum data and set that height to rest of the list items in the list.

How would i do that.. i have no clue on that.. Say if the 10th item has the maximum height i want to apply that height to the rest. help me implement this please and thank you for your support

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


Have an array of flags, say

boolean[] flags=new boolean[szieOfList];

fill this array to false;

Have a variable max height in your activity or adapter, say max, initialize it with 0 in onCreate method, now in getView method where you are inflating xml, write the following code:

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


来源:https://stackoverflow.com/questions/9807547/how-to-calculate-the-listview-item-height-at-run-time-and-set-all-items-with-sam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!