Skip to content Skip to sidebar Skip to footer

How To Calculate The Listview Item Height At Run Time And Set All Items With Same Height In Android?

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 ar

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

Post a Comment for "How To Calculate The Listview Item Height At Run Time And Set All Items With Same Height In Android?"