美文网首页Android开发经验谈Android实用技术
2019日更挑战(七),Android-View与ViewGro

2019日更挑战(七),Android-View与ViewGro

作者: Jlanglang | 来源:发表于2019-01-07 21:58 被阅读17次

瞎扯

说到View与ViewGroup,必讲的就是android中用到的一个非常重要的设计模式.
组合模式,
这点很形象.也很巧妙.

组合模式是什么

不扯别的,
就是把一个事物,分成2个体系,
一个是自身和各种子类实现,
一个是容器体系.也是其子类
举些例子:
1.文件,文件夹
2.树枝,树叶
3.物体,盒子.

细说:

1.文件,文件夹都是数据,但是文件夹可以装各种各样的文件.还可以装文件夹

2.树枝和树叶,这个其实不好解释.但确实可看成组合模式.

3.物体,盒子.盒子就是用来装物体的,而盒子也属于物体.盒子也可以单独存在.
这个是不是就比较好理解了.

常见的组合模式结构图

image.png

如果看上面的,不好理解.
那么代码怎么来表达呢.

public class Test {
  public class Wood {
        public String name() {
            return "木头";
        }

        public void printName() {
            String name = name();
            Log.i("name", name);
        }
    }

    public class Tree extends Wood {
        private List<Wood> childs = new ArrayList<>();

        public void add(Wood wood) {
            childs.add(wood);
        }

        public void remove(Wood wood) {
            childs.remove(wood);
        }

        public String name() {
            return "树枝";
        }

        public void printChildName() {
            printName();
            int size = getChilds().size();
            for (int i = 0; i < size; i++) {
                Wood wood = getChilds().get(i);
                if (wood instanceof Tree) {
                    ((Tree) wood).printChildName();
                } else {
                    wood.printName();
                }
            }
        }
    }

    public class Leaf extends Wood {
        public String name() {
            return "树叶";
        }
    }
}

test

    public void test() {
        //第一组
        Tree tree = new Tree();
        for (int i = 0; i < 3; i++) {
            tree.add(new Leaf());
        }
        //第二组
        Tree tree1 = new Tree();
        for (int i = 0; i < 4; i++) {
            tree1.add(new Leaf());
        }
        //总和
        Tree treeGroup = new Tree();
        treeGroup.add(tree);
        treeGroup.add(tree1);
    }

把上面的换成View,ViewGroup

 public void test(Context context) {
        //第一组
        ViewGroup tree = new LinearLayout(context);
        for (int i = 0; i < 4; i++) {
            tree.addView(new View(context));
        }
        //第二组
        ViewGroup tree1 = new LinearLayout(context);
        for (int i = 0; i < 3; i++) {
            tree1.addView(new View(context));
        }
        //总和
        LinearLayout treeGroup = new LinearLayout(context);
        treeGroup.addView(tree);
        treeGroup.addView(tree1);
    }

是不是一个意思.

总结:

View,ViewGroup.这么设计是非常符合OOP设计的.
View多种多样.但是有了ViewGroup.才能变化多端,各种组合.显示复杂的页面.
如果没有ViewGroup.想一想,每个复杂的页面都需要单独的View去完成.多不和谐.

组合的魅力在于.ViewGroup也是View的子类.也就是说它自己也是View.

所以.ViewGroup可以无限嵌套,添加.这样就有了无限种可能.

就如新的框架Flutter说的.万物皆Widget

就这样吧


您的喜欢与回复是我最大的动力-_-
交流群:493180098

相关文章

网友评论

    本文标题:2019日更挑战(七),Android-View与ViewGro

    本文链接:https://www.haomeiwen.com/subject/fneurqtx.html