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

前端 未结 2 991
梦谈多话
梦谈多话 2021-01-14 16:41

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 t

相关标签:
2条回答
  • 2021-01-14 16:53

    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.

    0 讨论(0)
  • 2021-01-14 17:00

    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());
    
    }
    
    0 讨论(0)
提交回复
热议问题