Android 在循环中引用自定义视图? [英] Android refer to custom views in a loop?

查看:33
本文介绍了Android 在循环中引用自定义视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要递归地遍历我的一堆扩展视图类的自定义视图.

I need to recursively move through a bunch of custom views of mine that extend the view class.

例如

ViewOne.java
ViewTwo.java
ViewThree.java

我在 MainClass.java 中创建了每个视图的实例

I have created instances of each view in my MainClass.java

ViewOne vOne;
ViewTwo vTwo;
ViewThree vThree;

这些视图都实现了一个名为 start() 的函数.

these views all implement a function called start().

我希望能够以某种方式遍历它们:

and I want to be able to loop through them somehow:

for(int i=0; i<= 2:i++)
{
  views[i].start();
}

我该怎么做?

以上只是一个例子.我需要能够以数字方式和编程方式在它们之间移动的真正原因是因为我希望能够在单击按钮(上一个和下一个)时按数字顺序向布局添加和删除视图.(我不希望它们一开始就全部添加到布局中,因为它们是资源密集型视图).

The above is only an example. The real reason I need to be able to move through them numerically and programatically is because I want to be able to add and remove views to a layout in their numeric order as button (previous and next) are clicked. (I don't want them all added to the layout at the start because they are heavily resource intensive views).

所以需要的是这样的:

单击下一步 -> 添加下一个视图 -> 删除当前视图.点击上一个 -> 添加上一个视图 -> 删除当前视图.

Click Next -> add next view -> remove current view. Click Previous -> add previous view -> remove current view.

例如

currView = 1

Current View is currView (1)
Click Next
Add View currView+1 (2) to Layout
Switch to View currView+1 (2)
Remove View currView (1)

or

currView = 2

Current View is currView (2)
Click Previous
Add View currView-1 (1) to Layout
Switch to currView-1 (1)
remove View currView (2)

注意,这些视图都是它们自己独特的类型,实际上是扩展视图的单个类.我不能简单地将它们类型转换为View",因为这是错误的,它们的类型分别是 ViewOne、ViewTwo 和 ViewThree(例如).

Note, this views are all of their own unique type and are infact individual classes that extend View. I can't simply typecast them to "View" because that's wrong, their types are ViewOne, ViewTwo and ViewThree respectively (for example).

推荐答案

假设所有视图都已添加到布局中,您可以像这样以编程方式遍历 ViewGroup(即布局)中的所有子项:

Assuming that all the views have been added to a layout, you can programatically iterate over all the children in a ViewGroup (i.e a layout) like so:

ViewGroup group = findViewById(R.id.root); // The name of your layout
int children = group.getChildCount();
for (int i = 0; i < children; i++) {

    View child = group.getChildAt(i);
    if (child instanceof ViewOne) {        
       ... 
    } else if (child instanceof ViewTwo) {
       ...
    }
}

此外,如果您的所有自定义视图都实现了 start(),我会将该方法推送到一个接口中,以便您可以简化上面的 if 块.

Additionally, if all of your custom views implement start(), I would push that method into an interface so you can simplify the if block above.

这篇关于Android 在循环中引用自定义视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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