Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

View 与 ViewGroup #16

Open
cnwutianhao opened this issue Feb 23, 2024 · 0 comments
Open

View 与 ViewGroup #16

cnwutianhao opened this issue Feb 23, 2024 · 0 comments
Labels

Comments

@cnwutianhao
Copy link
Owner

View 是 Android 所有控件的基类,我们平常所用的 TextView 和 ImageView 都是继承自 View 的,源码如下:

public class TextView extends View implements ViewTreeObserver.OnPreDrawListener {
    ...
}

public class ImageView extends View {
    ...
}

接着看看我们平常用的布局控件 RelativeLayout,它继承自 ViewGroup,源码如下所示:

public class RelativeLayout extends ViewGroup {
    ...
}

ViewGroup 又是什么呢?ViewGroup 可以理解为 View 的组合,它可以包含很多 View 以及 ViewGroup,而它包含的 ViewGroup 又可以包含 View 和 ViewGroup,依此类推,形成一个 View 树,如图1所示:

图1 View 树


需要注意的是 ViewGroup 也继承自 View,源码如下所示:

public abstract class ViewGroup extends View implements ViewParent, ViewManager {
    ...
}

ViewGroup 作为 View 或者 ViewGroup 这些组件的容器,派生了多种布局控件子类,比如 LinearLayout、RelativeLayout 等。一般来说,开发 Android 应用的 UI 界面都不会直接使用 View 和 ViewGroup,而是使用这两大基类的派生类。看图2我们就会有一个直观的了解:

图2 View 的部分继承关系


图2列举了 View 的部分继承关系,在这张图上我们看到 ViewGroup、TextView 等控件继承自 View,LinearLayout、RelativeLayout 等控件继承自 ViewGroup,TableLayout、RadioGroup 等控件继承自 LinearLayout,EditText、Button 等控件继承自 TextView,等等。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant