GridView doesn't contain all of adapter

ε祈祈猫儿з 提交于 2019-12-24 23:00:25

问题


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

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