Force onSizeChanged for ListView

北战南征 提交于 2019-12-04 05:24:34

To force onSizeChanged on ListView I do the following:

myList.getLayoutParams().height = myList.getHeight() + 1;
myList.requestLayout();

Just be sure to not call +1 or -1 everytime as the list may just overstretch the size specified and hence use a flag to toggle between +1 and -1.

Try with:

listView.requestLayout();

This is my solution:
I subclassed GridView with constructor (Context, AttributeSet):
(this for me must be done on a separate file class)
and overrided onSizeChanged method

MyGrid.java

public class MyGrid extends GridView {

  public void MyGrid(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub
  }

  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    // TODO Auto-generated method stub
    // Here I call my custom functions to prepare layout of my custom listview
    super.onSizeChanged(w, h, oldw, oldh);
  }
}

On class Activity than use GridView,
I have overrided onStart method
(called after OnCreate and after onRestart [when you came from another activity])

MyActivity.java

public class MyActivity extends Activity {

  onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(...)
    ...
  }
  ....

  protected void onStart() {
    // TODO Auto-generated method stub

    // call db and create cursor
    // 'mygridview' = findbyid MyGrid
    // (declared on xml like '<packagepath>'.mygrid

    // setadapter with my costom adapeter       

    // **HERE THE CALLED ONSIZECHANGED**
    // I make test proper for my app
    // (there is a simple test)
    if ('mygridview'.getMeasuredHeight() > 0) {
      // I use the same width and height for new and old measures
      // because for me that is right
      'mygridview'.onSizeChanged(gw.getWidth(), gw.getHeight(), 
                       gw.getWidth(), gw.getHeight());
    }
    super.onStart();
  }
}

With this approach, I can resize my grid at any time. I hope this you helpful.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!