How do I find the exact number of ListView items on the screen?

I would like the rows in the ListView to be sorted so that exactly six of them can fit on the screen. To do this, I need to know how much vertical space is available for the ListView (not the entire screen). However, the onCreate () measurement cannot be performed because views are not yet displayed.

If I take measurements after rendering, the ListView can be drawn and then resized, which can be distracting. What is the smartest way to set the required row height before displaying a ListView?

+4
source share
2 answers

onCreate 6. getView , suppost, id root , , a LinearLayout.

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View view = convertView;
    if(view == null){ some inflate }

    LinearLayout root = (LinearLayout) view.findViewById(R.id.root);
    LayoutParams lp = root.getLayoutParams();
    lp.height = screenHeight/6;
    root.setLayoutParams(lp);

    ....

    return view;
}

, , ListView . , .

: int heightForEachItem = (screenHeight - otherlayoutsHeightTogether) / 6;

+4

, ListView onGlobalLayout(). .

params = new AbsListView.LayoutParams(-1,-1);
listview.getViewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
    @Override
    public void onGlobalLayout(){ //this is called just before rendering
        params.height = listview.getHeight()/6; // this is what I was looking for
        listview.getViewTreeObserver.removeOnGlobalLayoutListener(this); // this is called very often
    }
adapter = new ArrayAdapter<...>(int position, ...){
    @Override
    public View getView(...){
        LinearLayout item = new LinearLayout(context);
        item.setLayoutParams(params);
        // add text, images etc with getItem(position) and item.addView(View)
        return item;
    }
}
listview.setAdapter(adapter);
0

Source: https://habr.com/ru/post/1568004/


All Articles