GridView getChildAt() 返回 null [英] GridView getChildAt() returns null

查看:18
本文介绍了GridView getChildAt() 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 GridView 获取视图.不幸的是,它返回 null.

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() 也返回 0!

我该怎么做才能获得此视图?我知道adapter里面有更改背景的选项,但是我得动态做.

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.

感谢您的帮助!

编辑

setAdapter:

gridview.setAdapter(new ImageAdapter(this));

图像适配器:

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 将在第一次布局过程中从适配器填充自身.这意味着它在 onCreate() 中不会有孩子.等待第一次布局传递的最简单方法是使用 ViewTreeObserver(请参阅 View.getViewTreeObserver())来注册全局布局侦听器.第一次调用侦听器时,网格应包含子项.

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.

请注意,如果您想更改 GridView 的其中一个子项的背景,您确实应该从适配器中进行.由于视图被回收,背景可能会在稍后移动"到另一个视图.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆