Android中View对象的实例化方式

Android中View对象的实例化,主要有以下四种方式:
(1)使用findViewById根据resId实例化View或者ViewGroup对象。

这种方式在根据xml生成View或ViewGroup对象时被普遍使用。不过,这种方式也存在较大限制,要求resId标识的视图必须严格是方法调用对象的子视图。

java 复制代码
View mView = parentView.findViewById(R.res.layout_star_view); 

(2)调用View.inflate,实例化View或者ViewGroup对象。
View.inflate主要用于自定义View场景,该方法的第三个参数为父视图,若该参数为null,或者传入的viewGroup的rootview为null,view.getLayoutParams()无法获取视图的布局参数。

java 复制代码
View view = View.inflate(this, R.layout.layout_pager_guide_1, null);

(3)调用inflater.inflate方法,动态实例化出View或者ViewGroup对象。

LayoutInflater的inflate方法,除了需要传入Context和Xml布局中的resId外,还有一个可选参数,用来标识生成的view是否需要挂载到父View上。如果该参数传入false,表示允许生成的View不添加到ViewGroup中,后续通过view.getLayoutParams()可以获得该视图的各种布局参数并允许通过代码动态调整。这对在RecyclerView等场景动态修改ViewHolder的布局参数非常有用。

java 复制代码
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.layout_star_view_item, parent, false);
复制代码
//获取LayoutInflater的三种方式
LayoutInflater inflater = getLayoutInflater(); //调用Activity的getLayoutInflater()
LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(context);

(4)重写Framgment的onCreateView方法,用inflater动态渲染view。

在Framgment等特定场景,inflater会从函数外部传入,开发者无需自己获取。

java 复制代码
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_square, null);
    initView(view);
    return view;
}
相关推荐
移动开发者1号1 小时前
ReLinker优化So库加载指南
android·kotlin
山野万里__1 小时前
C++与Java内存共享技术:跨平台与跨语言实现指南
android·java·c++·笔记
Huckings1 小时前
Android 性能问题
android
移动开发者1号2 小时前
剖析 Systrace:定位 UI 线程阻塞的终极指南
android·kotlin
移动开发者1号2 小时前
深入解析内存抖动:定位与修复实战(Kotlin版)
android·kotlin
whysqwhw2 小时前
OkHttp深度架构缺陷分析与革命性演进方案
android
Digitally4 小时前
如何将文件从 iPhone 传输到 Android(新指南)
android·ios·iphone
whysqwhw5 小时前
OkHttp深度架构缺陷分析与演进规划
android
用户7093722538515 小时前
Android14 SystemUI NotificationShadeWindowView 加载显示过程
android
木叶丸5 小时前
跨平台方案该如何选择?
android·前端·ios