I am trying to make ListView scroll background using ListView. I base my approach on this class on Shelves , but while in Shelves everything is the same height, I cannot make the same guarantee.
I have this activity:
public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.listView); List<String> items = new ArrayList<String>(); for(int i=0; i < 100; ++i) { items.add("Hello " + i); } CustomArrayAdapter adapter = new CustomArrayAdapter(this, items); listView.setAdapter(adapter); } }
Where is the CustomArrayAdapter:
public class CustomArrayAdapter extends ArrayAdapter<String> { private List<Integer> mHeights; public View getView(int position, View convertView, ViewGroup parent) {
What I want to do is fill mHeights in the adapter with the line height of the view.
My main attempt was to do this in getView ():
if(row.getMeasuredHeight() == 0) { row.measure( MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY)); } mHeights.set(position, row.getMeasuredHeight());
I tried several ways to do this, but I can't get anything to work.
In getView , if I call getHeight() , I get a return value of 0, and if I call getMeasuredHeight() , I get something non-zero, but not real height. If I scroll down and then again (taking one of the lines out of view) getHeight() == getMeasuredHeight() , and both have the correct value. If I just update mHeights in getView along the way (saying mHeights.set(position, row.getHeight() ); it works, but only after scrolling to the bottom of the list. I tried calling row.measure () in the getView method, but it all the same, getHeight() will be 0 on first run.
My question is this: how to calculate and populate mHeight with the correct ListView row height? I saw some similar questions, but they don't seem to be what I'm looking for. The ViewTreeObserver method seems promising, but I can't figure out how to force getView () calls to be invoked (alternately to iterate through ListView strings). The adapter.notifyDataSetChanged() call causes an infinite (albeit non-blocking) loop.
This is related to my previous question on this issue, which seems to have missed the point: ListView distance from the top of the list