naresh
naresh

Reputation: 155

android- How to get the width and height of the list view dynamically

In my application i want display list view using adapter. But i want get the current height and width of the list view (means after generating the list using adapter). how to get it. can anybody help me.

thanks

Upvotes: 3

Views: 5642

Answers (2)

OFFmind
OFFmind

Reputation: 637

To get current width or height of any view, you need to set onLayoutChange listener

public class MainActivity extends Activity implements OnLayoutChangeListener {

    private View newView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        newView = getLayoutInflater().inflate(R.layout.main_activity, null);
        newView.addOnLayoutChangeListener(this);
        setContentView(newView);
    }

    public void onLayoutChange(View v, int left, int top, int right,
            int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        //Here you can get size of you ListView, e.g:
        mylistView.getWidth();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        newView.removeOnLayoutChangeListener(this);
    }
}

27Nov15 - This is a good answer, I think you should release the resource too though. This might not matter so much for an Activity, but the same approach can be used by fragments where they may come and go more frequently.

Upvotes: 2

Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53657

Use getWidth() and getHeight() method of ListView in onWindowFocusChanged to get the width and height.

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);


    System.out.println("Width:" + listview.getWidth());
    System.out.println("Height:" + listview.getHeight());

}

Upvotes: 4

Related Questions