问题
I've made a GridView mGridView
and an adapter mAdapter
of 225 Views, and I set the adapter to the GridView. I also made a button so when I click on it does this:
Log.d("mAdapter.getCount()","" + mAdapter.getCount());
Log.d("mGridView.getCount()",""+mGridView.getCount());
Log.d("mGridView.getChildCount()",""+mGridView.getChildCount());
and there results are:
D/mAdapter.getCount()﹕ 225
D/mGridView.getCount()﹕ 225
D/mGridView.getChildCount()﹕ 180
This is a problem for me, because I need to use mGridView.getChildAt(int position)
from 0
to 224
. Whenever I use mGridView.getChildAt(180).setBackgroundColor(Color.BLUE)
I get this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundColor(int)' on a null object reference
It's saying that the child is null
. But I don't know how to fix this so I can access every child that's in the GridView.
回答1:
mGridView.getChildCount() would return the number of views visible at a time in the window. So say if my GridView has 5 columns and at a time only 10 could be displayed then mGridView.getChildCount() would return 50 (=5x10)
If you are trying to modify properties(say, backgroundColor) of a view at certain index using getChildCount API, you might probably check the first visible position(say, 25) using idxFirstVisiblePosition = mGridView.getFirstVisiblePosition(), then (idxFirstVisiblePosition + childCount - 1) would give you the maximum child index you could access and change properties for the current visible window.
来源:https://stackoverflow.com/questions/30146981/gridview-doesnt-contain-all-of-adapter