赞
踩
最近在跟着郭霖老师的第一行代码(第二版)在学习Android开发,在书中常常用到 kotlin-android-extensions 。
使用这个插件就可以直接用控件的id来调用控件实例,而不需要通过大量的 findViewById 来获取。
但在最新版本的AndroidStudio中,这个插件已经被弃用了,并且推荐使用 ViewBinding 来写。
这里对于为什么弃用 kotlin-android-extensions 插件不再多赘述,大概原理是这个插件原理通过维护一个哈希表来实现缓存增加了内存开支,另外哈希表的get也并非真正的O(1)方法,在郭霖老师的博客中通过反编译来获取这个插件的原理,对该原因有更加详细的描述。郭霖老师的DLC
ViewBinding能达成和该插件类似的结果,并且只是通过事先的一个 inflate 操作,从而可以用一个View实例binding的属性来调用控件实例。
具体的代码风格来说如下所示:
- package com.example.activitytest
-
- import androidx.appcompat.app.AppCompatActivity
- import android.os.Bundle
- import android.view.View
- import android.widget.Button
- import android.widget.Toast
- import androidx.appcompat.app.AlertDialog
- import com.example.activitytest.databinding.ActivityMainBinding
-
- class FirstActivity : AppCompatActivity() {
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- val binding = ActivityMainBinding.inflate(layoutInflater)
- setContentView(binding.root)
-
- supportActionBar?.hide()
- val inputText = binding.editText.text
- binding.button.setOnClickListener{
- Toast.makeText(this, inputText, Toast.LENGTH_SHORT).show()
-
- binding.image.setImageResource(R.drawable.ic_launcher_foreground)
- if (binding.progressBar.visibility == View.VISIBLE) {
- binding.progressBar.visibility = View.INVISIBLE
- } else {
- binding.progressBar.visibility = View.VISIBLE
- }
- binding.progressBar.progress += 10
-
- AlertDialog.Builder(this).apply {
- setTitle("This is a Dialog")
- setMessage("Something important")
- setCancelable(false)
- setPositiveButton("OK") {
- dialog, which ->
- }
- setNegativeButton("Cancel") {
- dialog, which ->
- }
- show()
- }
- }
-
-
- }
-
-
-
- }

在上面这段代码中,通过一个 ActivityMainBinding.inflate() 语句(对每个xml文件改为驼峰书写加上Binding均可获得对应binding类)可以获得该View实例 binding ,后续便可通过 binding.editText 来获取xml中的输入框的属性,其他控件同理。
看一下 inflate() 语句具体再做些什么,我们通过看他的定义,如下:
- public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
- final Resources res = getContext().getResources();
- if (DEBUG) {
- Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
- + Integer.toHexString(resource) + ")");
- }
-
- View view = tryInflatePrecompiled(resource, res, root, attachToRoot);
- if (view != null) {
- return view;
- }
- XmlResourceParser parser = res.getLayout(resource);
- try {
- return inflate(parser, root, attachToRoot);
- } finally {
- parser.close();
- }
- }

我们可以看到这里需要传参一个resource的id,一个ViewGroup的根(父)view,以及一个表示是否加入到根(父)view的布尔变量。
然后获取View实例的关键点在于 try 中的 inflate() 方法,我们再去看看这个方法:
- public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
- synchronized (mConstructorArgs) {
- Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
-
- final Context inflaterContext = mContext;
- final AttributeSet attrs = Xml.asAttributeSet(parser);
- Context lastContext = (Context) mConstructorArgs[0];
- mConstructorArgs[0] = inflaterContext;
- View result = root;
-
- if (root != null && root.getViewRootImpl() != null) {
- root.getViewRootImpl().notifyRendererOfExpensiveFrame();
- }
-
- try {
- advanceToRootNode(parser);
- final String name = parser.getName();
-
- if (DEBUG) {
- System.out.println("**************************");
- System.out.println("Creating root view: "
- + name);
- System.out.println("**************************");
- }
-
- if (TAG_MERGE.equals(name)) {
- if (root == null || !attachToRoot) {
- throw new InflateException("<merge /> can be used only with a valid "
- + "ViewGroup root and attachToRoot=true");
- }
-
- rInflate(parser, root, inflaterContext, attrs, false);
- } else {
- // Temp is the root view that was found in the xml
- final View temp = createViewFromTag(root, name, inflaterContext, attrs);
-
- if (root == null && temp != null && temp.getViewRootImpl() != null) {
- temp.getViewRootImpl().notifyRendererOfExpensiveFrame();
- }
-
- ViewGroup.LayoutParams params = null;
-
- if (root != null) {
- if (DEBUG) {
- System.out.println("Creating params from root: " +
- root);
- }
- // Create layout params that match root, if supplied
- params = root.generateLayoutParams(attrs);
- if (!attachToRoot) {
- // Set the layout params for temp if we are not
- // attaching. (If we are, we use addView, below)
- temp.setLayoutParams(params);
- }
- }
-
- if (DEBUG) {
- System.out.println("-----> start inflating children");
- }
-
- // Inflate all children under temp against its context.
- rInflateChildren(parser, temp, attrs, true);
-
- if (DEBUG) {
- System.out.println("-----> done inflating children");
- }
-
- // We are supposed to attach all the views we found (int temp)
- // to root. Do that now.
- if (root != null && attachToRoot) {
- root.addView(temp, params);
- }
-
- // Decide whether to return the root that was passed in or the
- // top view found in xml.
- if (root == null || !attachToRoot) {
- result = temp;
- }
- }
-
- } catch (XmlPullParserException e) {
- final InflateException ie = new InflateException(e.getMessage(), e);
- ie.setStackTrace(EMPTY_STACK_TRACE);
- throw ie;
- } catch (Exception e) {
- final InflateException ie = new InflateException(
- getParserStateDescription(inflaterContext, attrs)
- + ": " + e.getMessage(), e);
- ie.setStackTrace(EMPTY_STACK_TRACE);
- throw ie;
- } finally {
- // Don't retain static reference on context.
- mConstructorArgs[0] = lastContext;
- mConstructorArgs[1] = null;
-
- Trace.traceEnd(Trace.TRACE_TAG_VIEW);
- }
-
- return result;
- }
- }

这里虽然比较长,但是核心代码部分还是非常清晰的:
当root不为空时,根据resource的最外层view在xml中定义的的属性,创建布局参数params。如果attachToRoot=False,则为temp设置布局参数params。
而当root不为空而且attachToRoot=True时,将temp添加到root中,并使用上面创建的布局参数params。
当root为空时候或者attachToRoot=False,将temp赋值给result。
最后,将result返回。
后续是我遇到的问题,我在自定义titleBar控件(第一行代码第四章中的实例)并在MainActivity中引用时候发生了控件不可用(按钮失效)的问题。
- package com.example.activitytest
-
- import android.app.Activity
- import android.content.Context
- import android.util.AttributeSet
- import android.view.LayoutInflater
- import android.widget.LinearLayout
- import android.widget.Toast
- import com.example.activitytest.databinding.TitleBinding
-
-
- class TitleLayout(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs){
-
- init {
- LayoutInflater.from(context).inflate(R.layout.title, this)
- val binding = TitleBinding.inflate(LayoutInflater.from(context), this, true)
-
- binding.titleBack.setOnClickListener {
- val activity = context as Activity
- activity.finish()
- }
-
- binding.titleEdit.setOnClickListener {
- Toast.makeText(context, "You clicked the edit button.", Toast.LENGTH_SHORT).show()
- }
-
- }
-
-
-
- }

我在不断修改初始化代码块的前两行代码(Binding部分),偶然在修改为如下代码时发现控件运行正常了:
LayoutInflater.from(context).inflate(R.layout.title, this, false)
回归源码去思考为什么这个第三个参数 attachToRoot 采用缺省值(True)会造成这样的结果,两种代码相差了一句代码:
root.addView(temp, params);
也就是说在root不为空时,我把先前的 params 参数传入 rootView 中则会造成未给该组件分配参数的问题,所以需要 attachToRoot 传参 False ,至此问题解决了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。