Pages

Subscribe:

Labels

Wednesday, 28 September 2011

Dynamically change the ListView height - Android

This post is used to change the ListView height. This is done depends on the childviews .
 This Utility.java class is like this


 import android.view.View;
import android.view.ViewGroup;
import android.view.View.MeasureSpec;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Utility {
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
}



In the main Acticity use this Utility class to change the listview height.

 phraseListView=(ListView)findViewById(R.id.phrase_listview);
 phraseAdapter=new PhraseListAdapter(this);
phraseListView.setAdapter(phraseAdapter);
Utility.setListViewHeightBasedOnChildren(phraseListView);
       

10 comments:

Abarshini said...

Thanks for providing really nice information



Android Training

Jesus Alberto said...

Thank you very much!

Vishal gupta said...

ooo guys u rock it

soumen mohar said...

thank u

Slackneo said...

OMG!!! Thank u!!!!!

John Victor said...

Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..
Android Training in Chennai

isabellaJoseph said...

LEARN | GET JOB | HAPPY LIFE @ TIS Academy
Thank you so much for sharing. it’s useful for me.
Dot Net Training in Chennai
Android Training in Chennai

Dot Net Training in Chennai


Swathy Vignesh said...

hi welcome to this blog. really you have post an informative blog. it will be really helpful to many peoples. thank you for sharing this blog.
java training in chennai

Swathy Vignesh said...

hi welcome to this blog. really you have post an informative blog. it will be really helpful to many peoples. thank you for sharing this blog.
java training in chennai

Logavani G said...

hi welcome to this blog. really you have post an informative blog. it will be really helpful to many peoples. thank you for sharing this blog.
selenium training in chennai

Post a Comment