List<View> 值得吗?

Is List<View> worth it?

问题

我有一个自定义 activity,它从 XML 文件中加载图形,其中我有很多按钮、图像和文本。

我的实施计划

为了实现,我想使用 android 类,例如 ImageButtonTextViewImageView

我想使用 List<View> 来循环所有 View 对象并膨胀成 RelativeLayout

我的疑惑

List<View>List<ImageButton>List<TextView>List<ImageView> 哪个更好?

ImageButtonImageView 中的方法实现(如 onClick 或其他事件),当我将其转换为 View 对象时会丢失?

我计划的代码示例:

ImageButton imageButton = new ImageButton(getContext());

//Implementation of methods and events...
List<View> list = new ArrayList<View>;
list.add(imageButton);

该列表仅包含您的组件的引用。如果您为 exmaple 创建一个 ImageButton,设置一个点击侦听器并将其添加到 List<View>,什么都不会丢失。唯一的问题是您不知道每个视图的实际类型。

要获得通用 View 的真实 class,您可以使用多个 if 语句来检查所有组件类型,例如:

if (view instanceof ImageButton) {
    ImageButton imageButton = (ImageButton)view;
}

instanceof 检查对象是否属于特定的 class 或扩展它。因此,请确保先检查 ImageButton,然后再检查 ImageView,例如,因为它是 class.

的后代

你最大的疑惑是

Method implementation in ImageButton or ImageView (Like onClick or some other event), is lost when I convert it to a View object?

不,这不会发生。

考虑两个 classes

class Parent{
    void big(){}
}

class Child extends Parent{
    void small(){}
}

如果你说

Child c = new Child();

那么你可以使用

c.big(); 以及 c.small();

但如果你说

Parent c = new Child();

您可以使用

c.big();

但是在 Child 中调用 small() class 你需要施放它

Child ch = (Child)c;
ch.small();

现在如果有多个子classes,每个子都有不同的可用方法 像 Child1small1()Child2small2() 等等然后你可以使用 instanceof 铸造

喜欢

if(ch1 instanceof Child1)
{   
    Child1 c1 = (Child1)ch1;
    c1.small1();
}
if(ch2 instanceof Child2)
{
    Child2 c2 = (Child2)ch2;
    c2.small2();
}