如何在Android中以编程方式替换视图? [英] How to replace view programmatically in Android?

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

问题描述

我有一个复杂的视图,其中包含几个子视图,例如文本视图和图像视图. 我想用另一个(派生的)图像视图替换其中一个图像视图(另一个视图支持在后台加载图像).

I have a complex view, containing several subviews, like text views and image views. I'd like to replace one of the image views with another (derived) image view (the other one support loading images in the background).

如何用新的视图替换原始图像视图?

我目前拥有的解决方案是复制粘贴整个XML布局,然后在新XML中进行替换-非常糟糕,无法重复使用并且不重用:(

The solution I currently have is just copy pasting the whole XML layout and do the replace in the new XML - Very bad to duplicate and not reuse things :(

推荐答案

我不太确定我能理解您的意思,但是如果您只是想从布局中删除View的一个实例并与另一个实例交换它,可以使用这样的实用程序类:

I'm not really sure that I understand what you're saying but if you simply wanna remove one instance of View from a layout and exchange it with another you could use a utility class like this:

import android.view.View;
import android.view.ViewGroup;

public class ViewGroupUtils {

    public static ViewGroup getParent(View view) {
        return (ViewGroup)view.getParent();
    }

    public static void removeView(View view) {
        ViewGroup parent = getParent(view);
        if(parent != null) {
            parent.removeView(view);
        }
    }

    public static void replaceView(View currentView, View newView) {
        ViewGroup parent = getParent(currentView);
        if(parent == null) {
            return;
        }
        final int index = parent.indexOfChild(currentView);
        removeView(currentView);
        removeView(newView);
        parent.addView(newView, index);
    }
}

跟进问题:当您说很难复制且不能重复使用"时,您是什么意思?您知道包含标记吗?

Follow-up question: What do you mean when you're saying "Very bad to duplicate and not reuse"? Are you aware of the include tag?

这篇关于如何在Android中以编程方式替换视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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