当前位置:网站首页>Dynamically set the layoutinflater of the layout
Dynamically set the layoutinflater of the layout
2022-06-11 14:55:00 【Ant】
Dynamically set the layout LayoutInflater
Recently doing Android project , There is no time to start from scratch , Most of the knowledge points can only be accumulated at the same time . Today, when writing the layout of a requirement, we are
KatoUse... At the suggestion of classmatesRecyclerViewTo achieve , Come into contact with during the coding processLayoutInflaterThis thing , It is also the first contact , Sort out relevant knowledge points .
What is? LayoutInflater
LayoutInflater It's a Is used to xml The layout file is loaded as View perhaps ViewGroup Tools for objects , We can call it ** Layout loader **.
take layout Of xml The layout file is instantiated as View Class object ,LayoutInflater Is similar to findViewById(), The difference is LayoutInflater It's used to find layout Under folder xml Layout file , And instantiate ! and findViewById() Is to find a specific one xml The details are as follows widget Control ( Such as :Button,TextView etc. ).
Access method
LayoutInflater Itself is an abstract class , Not directly through new To get its instance .
Code up :
The first method
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
The second method
LayoutInflater inflater = LayoutInflater.from(context);
The third method
// stay Activity Internal calls getLayoutInflater() Method
These three ways are essentially the same , You can see it in the source code :
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
} stay Activity Internal calls getLayoutInflater Method actually calls PhoneWindow Of mLayoutInflater:
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
} These methods actually lead to the same goal , All by calling Context Of getSystemService Method to get .
What you get is PhoneLayoutInflater This implementation class .
public class Policy implements IPolicy {
...
public LayoutInflater makeNewLayoutInflater(Context context) {
return new PhoneLayoutInflater(context);
}
} Instantiation View Class object
Instantiation LayoutInflater after , will layout Of xml The layout file is instantiated as View Class object .
View view=inflater.inflate(R.layout.ID, null);
inflate Method
Click to enter sdk Source code , You can find inflate Methods have the following overloaded methods :
The values they return are View object .
among public View inflate (int resource, ViewGroup root) Most commonly used .
Sample code :
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test)); //EditText editText = (EditText)findViewById(R.id.content);// error EditText editText = (EditText)view.findViewById(R.id.content);
The second parameter is specified ViewGroup root, Of course, you can set it to null value .
inflate Method parameter relationship
root != null, attachToRoot == trueThe incoming layout will be loaded as a View And as a child View Add to root in , Eventually return root; And the root node of this layout android:layout_xxx Parameters will be parsed to set View Size ;root == null, attachToRoot meaninglessWhen root It's empty time ,attachToRoot No matter what it is, it doesn't make sense . At this point, the passed in layout will be loaded into a View And return directly ; Layout root View Ofandroid:layout_xxxAttributes are ignored , namely android:layout_xx Attributes can only be attached to a ViewGroup In order to take effect ;root != null, attachToRoot == falseThe incoming layout will be loaded as a View And return directly . Layout root View Ofandroid:layout_xxxThe property will be resolved to LayoutParams And set it in View On , here root Only used to set the layout root View The size and location of .
load xml The principle of layout
Start at the root node , Recursive parsing xml Each node of .
The process of recursion at each step is : By node name ( Full class name ), Use ClassLoader Create an instance of the corresponding class , That is to say View, then , Put this View Add to its upper nodes ( Father View).
At the same time, the corresponding xml The attributes of the node are View Properties of . Each level of nodes will be generated one by one View, And according to View The hierarchy of add To the corresponding immediate parent View( Upper node ) in , Finally, it returns a child that contains all the parsed results View The layout root of View.
Reference material
- Knowledge point : Dynamic layout LayoutInflater
- Official documents
- understand Android Medium LayoutInflater
Sharing plans
Blog content will be synchronized to Tencent cloud + Community , Invite everyone to join us :https://cloud.tencent.com/
license agreement
In this paper A signature - Noncommercial use - Share in the same way 4.0 The international license agreement , Reprint please indicate the source .
边栏推荐
- Explain the kubernetes package management tool Helm
- 2022 simulated 100 questions and simulated examination of quality officer municipal direction post skills (Quality Officer) examination
- Flutter 3.0 was officially released: it stably supports 6 platforms, and byte jitter is the main user
- LeetCode每日一题——加一
- 树莓派获得网络安装系统功能,无需借助其他设备
- 01discussion on Tekton
- 清北力压耶鲁,MIT蝉联第一,2023QS世界大学排名最新发布
- Basic configuration command of Xinhua 3 switch system
- 汤峥嵘:CTO 是商业思维和技术思维交汇的那个点
- 2021 年 CNCF 调查:Kubernetes 跨越鸿沟的一年
猜你喜欢

回溯法/解空间树 排列树

What is excess product power? Find the secret key of the second generation cs75plus in the year of the tiger

对于事务的认识

Uniapp settings page Jump effect - navigateto switching effect - Global animationtype animation
![[verification of SystemVerilog] ~ test platform, hardware design description, excitation generator, monitor and comparator](/img/3a/0cc26400eeb4b388face09b9a10f27.png)
[verification of SystemVerilog] ~ test platform, hardware design description, excitation generator, monitor and comparator

【SystemVerilog 之 过程块和方法】~ 域、always过程块、initial过程块、函数 function、任务 task、生命周期

Online "comment explicit" function, TME's wave point music cultivates music "private plots"

腾讯面试官分享面试经验,如何考察面试者技术及个人综合素质,给正在面试的你一点建议

大道至简 | 设计 ViT 到底怎么配置Self-Attention才是最合理的?

Avenue to Jane | Comment concevoir un vit pour configurer l'auto - attraction est - il le plus raisonnable?
随机推荐
Current situation and future development trend of global and Chinese transcranial magnetic stimulation coil Market from 2022 to 2028
Ali, tell me about the application scenarios of message oriented middleware?
数据库优化
【SystemVerilog 之 验证】~ 测试平台、硬件设计描述、激励发生器、监测器、比较器
回溯法/活动安排 最大兼容活动
Online "comment explicit" function, TME's wave point music cultivates music "private plots"
MySQL create table error 1067 - invalid default value for 'update_ time‘
Implementation of gray-scale publishing scheme for microservice architecture based on gateway and Nacos
System. out. What should I pay attention to when using the println () method
Hashicopy之nomad应用编排方案02
Summary of some classic embedded C interview questions
Raspberry pie obtains the function of network installation system without the help of other devices
清北力压耶鲁,MIT蝉联第一,2023QS世界大学排名最新发布
Database optimization
A former employee of Baidu was awarded 1.07 million yuan for job hopping; Apple, Google and Microsoft plan to "kill" the password; It is said that Geely has acquired Meizu | Q information
Why do I need the public static void main (string[] args) method?
Repository Manager之Nexus配置yum仓库
01discussion on Tekton
[verification of SystemVerilog] ~ test platform, hardware design description, excitation generator, monitor and comparator
Current situation and future development trend of global and Chinese metal casting robot market