GridView getChildAt() 返回 null

编程入门 行业动态 更新时间:2024-10-12 03:23:08
本文介绍了GridView getChildAt() 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试从 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-01 10:19:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/828847.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:GridView   getChildAt   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!