GridView的getChildAt()返回null [英] GridView getChildAt() returns null
问题描述
我想从GridView的视图。不幸的是,它返回空
。
的onCreate():
的GridView的GridView =(GridView控件)findViewById(R.id.gridView);
gridview.getChildAt(3).setBackgroundResource(R.drawable.list_selector_holo_light);
gridview.getChildCount()
返回0呢!
我能做些什么让这个观点?我知道,有一个选项,以更改适配器的背景,但我必须动态地做到这一点。
感谢您的帮助!
修改的
setAdapter:
gridview.setAdapter(新ImageAdapter(本));
ImageAdapter:
公开查看getView(INT位置,查看convertView,ViewGroup中父){
最后的ImageView ImageView的;
如果(convertView == NULL){//如果它不回收,初始化一些属性
ImageView的=新ImageView的(mContext);
imageView.setLayoutParams(新GridView.LayoutParams(85,85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8,8,8,8);
} 其他 {
ImageView的=(ImageView的)convertView;
}
imageView.setImageResource(mThumbIds [位置]);
返回ImageView的;
}
的GridView
将在第一个布局传递过程中填充自己的适配器。这意味着它不会在的onCreate儿童()
。等待第一个布局传递的最简单的方法是使用 ViewTreeObserver
(见 View.getViewTreeObserver()
)以注册一个全球布局的听众。第一次监听被调用,电网应包含的孩子。
请注意,如果你想改变一个的GridView的孩子中的一个背景
你真的应该从适配器做到这一点。由于意见回收的背景可能会出现搬家另一种观点以后。
I'm trying to get a View from GridView. Unfortunately, it returns null
.
onCreate():
GridView gridview = (GridView) findViewById(R.id.gridView);
gridview.getChildAt(3).setBackgroundResource(R.drawable.list_selector_holo_light);
gridview.getChildCount()
returns 0 too!
What can I do to get this View? I know that there is an option to change the background in the Adapter, but I have to do it dynamically.
Thanks for help!
EDIT
setAdapter:
gridview.setAdapter(new ImageAdapter(this));
ImageAdapter:
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
GridView
will populate itself from the adapter during the first layout pass. This means it won't have children in onCreate()
. The easiest way to wait for the first layout pass is to use a ViewTreeObserver
(see View.getViewTreeObserver()
) to register a global layout listener. The first time the listener is invoked, the grid should contain children.
Note that if you want to change the background of one of the children of a GridView
you really should do it from the adapter. Since views are recycled the background may appear to "move" to another view later on.
这篇关于GridView的getChildAt()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!