从在 Android 中以编程方式创建的父视图中查找子视图 [英] Finding child views from parent view created programmatically in Android

查看:27
本文介绍了从在 Android 中以编程方式创建的父视图中查找子视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 Android 应用程序,我使用 GridView 并扩展 BaseAdapter 来组织其内容.对于我在扩展 BaseAdapter 类中重写的函数 getView,我创建了一个 LinearLayout,我将一个 ImageView 和 3 个 TextView 附加到它.现在,我需要实现 convertView,但是因为我以编程方式创建了我的视图,所以我不认为我可以使用 findViewById 来查找这些子视图来更改它们的属性(如文本和位图).

For an Android App, I'm using a GridView and extending BaseAdapter to organize its contents. For the function getView that I override in my extended BaseAdapter class, I create a LinearLayout, which I attach an ImageView and 3 TextViews to. Now, I need to implement convertView, but because I created my views programmatically, I didn't think I can use findViewById to find these child views to change their properties (like text and bitmaps).

我想在创建视图时为每个视图分配一个与不同类型视图相关的唯一 ID(例如:将我的名称 textview 的 id 指定为 1,将描述 textview 的 id 指定为 2 等),但我是不确定每个视图中的 id 是否必须是唯一的,无论它们是否是同一种视图.

I had the idea of assigning a unique ID pertaining to different types of views for each one when I create them (example: give my name textview the id of 1, description textview the id of 2, etc), but I was not sure if the ids have to be unique among every view, whether they're the same kind of view or not.

最终,我如何找到属于以编程方式创建的线性布局视图的一部分的子视图?

Ultimately, how do I find a child view that's part of a linearlayout view which were all created programmatically?

推荐答案

你可以通过 getChildAt() 但很难区分你到底得到了什么孩子.

You can get children of LinearLayout via getChildAt() but it's hard to distinguish what child exactly you get.

我认为分配 ID 是更好的方法.您可以为视图分配 ID,然后通过 findViewById() 获取视图.每个 LinearLayout 的 ID 不需要是唯一的.

I think assigning IDs is better way. You can assign IDs to your views and later get views via findViewById(). IDs doesn't need to be unique for each LinearLayout.

像这样:

// Give more sensible names to ID's
int IMAGEVIEW_ID = 0;
int TEXTVIEW1_ID = 1;
int TEXTVIEW2_ID = 2;
int TEXTVIEW3_ID = 3;

imageView.setId(IMAGEVIEW_ID);
textView1.setId(TEXTVIEW1_ID);
textView2.setId(TEXTVIEW2_ID);
textView3.setId(TEXTVIEW3_ID);

...
// somewhere later
ImageView imageView = (ImageView) convertView.findViewById(IMAGEVIEW_ID);

这篇关于从在 Android 中以编程方式创建的父视图中查找子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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