LayoutInflater学习(二)之创建布局View

LayoutInflater Factory创建自定义View LayoutInflater Factory的介绍 LayoutInflater类中有三个关于Factory的变量 @UnsupportedAppUsage private Factory mFactory; @UnsupportedAppUsage private Factory2 mFactory2; @UnsupportedAppUsage private Factory2 mPrivateFactory; 在Activity中设置setContentVie 阅读详情

这篇是在上篇的基础上继续学习LayoutInflater,上篇主要讲了LayoutInflater是怎么解析布局的,但是并没有去仔细地说明LayoutInflater创建View的过程,这篇就补上这部分。

LayoutInflater创建xml布局View是分开创建的:

1. 先创建xml布局最外层的View,也就是布局的根View

2. 递归创建所有的子View

本着先简后繁的原则,先不考虑 <merge> <include>等标签,直接从一般情况的流程看起

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
           ......
            View result = root;
            try {
               ......
                if (TAG_MERGE.equals(name)) {
                    ......
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    //首先创建xml布局最外层View:根View
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    //递归创建子View
                    // Inflate all children under temp against its context.
                    rInflateChildren(parser, temp, attrs, true);
                    ......
                }
            } catch (XmlPullParserException e) {
            ......
            return result;
        }
    }

布局根View的创建

布局最外层根View的创建是通过 createViewFromTag() 来创建的,其实后面子View的创建依然会用到这个方法,在看这个方法之前先理清方法的参数.

第一个参数 root :这里注意:这个 root 是我们调用LayoutInflater的inflate方法加载布局时自己传入的一个父View,需要和要加载的xml布局根View区分开来

第二个参数 name:这个是对应我们要解析的xml布局树中对应的每个View的名称,就以上篇文章中 activity_main.xml 为例,name 的取值为

androidx.constraintlayout.widget.ConstraintLayout,当然如果是子View的创建取值将依次为:LinearLayout、TextView、FrameLayout

后面两个参数依次为上下文 Context 和保存要创建View的属性的 AttributeSet 对象,接下来开始看代码,还是只看主要流程


    private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
        return createViewFromTag(parent, name, context, attrs, false);
    }
    View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
       ......
        try {
            //这里可以通过设置工厂的形式拦截系统创建View
            View view = tryCreateView(parent, name, context, attrs);
            if (view == null) {
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    if (-1 == name.indexOf('.')) {
                        //SDK View的创建,eg:LinearLayout TextView ...
                        view = onCreateView(context, parent, name, attrs);
                    } else {
                        //自定义View的创建,eg:androidx.constraintlayout.widget.ConstraintLayout
                        view = createView(context, name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }
            return view;
        } catch (InflateException e) {
        ......
    }

首先来看下这个 tryCreateView ,这个方法其实是系统创建View的一个Hook点

   private boolean mFactorySet;
   private Factory mFactory;
   private Factory2 mFactory2;
   private Factory2 mPrivateFactory;
   public final View tryCreateView(@Nullable View parent, @NonNull String name,
        @NonNull Context context,
        @NonNull AttributeSet attrs) {
        ......
        View view;
        if (mFactory2 != null) {
            view = mFactory2.onCreateView(parent, name, context, attrs);
        } else if (mFactory != null) {
            view = mFactory.onCreateView(name, context, attrs);
        } else {
            view = null;
        }
        if (view == null && mPrivateFactory != null) {
            view = mPrivateFactory.onCreateView(parent, name, context, attrs);
        }
        return view;
    }

 tryCreateView 中首先通过 mFactory2 来创建View, mFactory2 是LayoutInflater的一个成员变量,Factory2是一个接口,平时我们使用LayoutInflater来加载布局的时候 tryCreateView方法一般都是返回 null 的,我们可以自己实现这个接口,并通过对应的 setFactory2()方法设置到LayoutInflater中,这样可以拦截系统创建xml布局View的过程,不过这个setFactory2的方法只能设置一次,因为mFactorySet的控制,再次设置会抛出异常,这里也可以通过反射消除这个异常,后面的mFactory也是类似的,mPrivateFactory 其实Activity已经实现了 不过onCreateView方法直接返回null了,对于系统创建 xml 布局的Hook点就说到这里,对此感兴趣的朋友可以去看下对应源码

接下来看第二个try语句中的逻辑,也就是 if..else..语句,这才是系统创建View的核心逻辑,这里对要创建的View做了个分类,看看要创建的View是开发者自定义的View,还是SDK中的系统View,一般我们使用自定义View的时候 name 值往往是 com.xxx.xx.XxxView,所以这里通过判断 name 中是否包含 "." 来判断是不是自定义View,像LinearLayout、TextView、FrameLayout、RelativeLayout等这些都是SDK View,有人可能会问了,那上面的约束布局 ConstraintLayout 又该怎么算呢,ConstraintLayout 的 name 中包含了".",当然它也是自定义View,只不过是google工程师自定义的。

为什么要区分SDK View和自定义View,这是因为后面创建View对象都是通过反射,需要View的全类名,而SDK View在不同的包下,需要手动拼接全类名

 先来看SDK View 的创建流程,会通过多个重载的方法:onCreateView方法来创建View

   public View onCreateView(@NonNull Context viewContext, @Nullable View parent,
            @NonNull String name, @Nullable AttributeSet attrs)
            throws ClassNotFoundException {
        return onCreateView(parent, name, attrs);
    }
   protected View onCreateView(View parent, String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return onCreateView(name, attrs);
    }

流程走到这里需要注意下了:看过第一篇文章的朋友应该知道,我们加载布局最终获取到的是PhoneLayoutInflater对象,所以后面的流程不在LayoutInflater这个类里面,而是要到 PhoneLayoutInflater里去,虽说不是很难找到,但是也是比较容易忽略的一个点,稍微提下。

public class PhoneLayoutInflater extends LayoutInflater {
    private static final String[] sClassPrefixList = {
        "android.widget.",
        "android.webkit.",
        "android.app."
    };   
    @Override
    protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
        for (String prefix : sClassPrefixList) {
            try {
                View view = createView(name, prefix, attrs);
                if (view != null) {
                    return view;
                }
            } catch (ClassNotFoundException e) {
               ......
            }
        }
        return super.onCreateView(name, attrs);
    }
}

细心的朋友可能发现了,这个 sClassPrefixList 数组里好像少了一个 "android.view." 的包,这个参数其实是加在了超类LayoutInflater里,有兴趣的可以看下就不再贴源码了,这里循环遍历了SDK View的包名 prefix,之后作为参数传到了createView方法中,接下来又进入了LayoutInflater的方法中,其核心代码如下

   public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        Context context = (Context) mConstructorArgs[0];
        if (context == null) {
            context = mContext;
        }
        return createView(context, name, prefix, attrs);
    }

    public final View createView(@NonNull Context viewContext, @NonNull String name,
            @Nullable String prefix, @Nullable AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        ......
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        ......
        Class<? extends View> clazz = null;
        try {
            if (constructor == null) {
                //反射获取对应View的Class对象
                clazz = Class.forName(prefix != null ? (prefix + name) : name, false,
                        mContext.getClassLoader()).asSubclass(View.class);
                ......
                //获取创建View的构造器
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                sConstructorMap.put(name, constructor);
            } else {
               ......
            }
            Object lastContext = mConstructorArgs[0];
            mConstructorArgs[0] = viewContext;
            Object[] args = mConstructorArgs;
            args[1] = attrs;
            try {
                //通过View的构造器反射创建View对象
                final View view = constructor.newInstance(args);
                if (view instanceof ViewStub) {
                    final ViewStub viewStub = (ViewStub) view;
                    viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
                }
                return view;
            } finally {
                mConstructorArgs[0] = lastContext;
            }
        } catch (NoSuchMethodException e) {
        ......
    }

最终SDK View的创建和自定义View的创建都是通过 createView(Context viewContext, String name, String prefix, AttributeSet attrs) 方法来创建的,只不过SDK View需要先获取到对应的包名,再拼接获取到全类名之后再调用该方法创建View

通过反射获取对应View的Class对象时,SDK View会对全类名做一个拼接, 而自定义View prefix为null,因为在xml布局获取到的 name 就是自定义View的全类名,当通过构造器的newInstance方法创建View时,会调用对应View的构造方法,由于传入的参数 args 是一个包含两个元素的数组,这两个元素分别是Context上下文和属性集合Attributeset对象,所以最终会调用每个View的两参构造函数,例如 TextView 将会调用如下构造方法,其他View也一样

    public TextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.textViewStyle);
    }

这就是为什么我们写自定义View时必须要有这个两参的构造函数,否则就会报错,到此两种类型View的创建流程都走完了

递归创建子View

递归创建子View的方法是 rInflateChildren(),这个方法是在inflate()方法中创建完xml的根View后调用的,另外在rInflate()方法中也调用了一次,这一次是为了实现递归,还有就是在解析 include 标签的 parseInclude()方法中也调用了这个方法,我们先了解在 inflate()方法中的调用,在看这个方法之前还是要先了解下它的参数,重点关注下第二个参数,在 inflate()方法中传入的是 temp,而 temp 就是xml布局的根View,这里同样要和父容器root 区分开来。

一般递归流程

还是先从一般的简单流程看,不考虑xml中其他标签,这个之后再讨论

   final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
            boolean finishInflate) throws XmlPullParserException, IOException {
        rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
    }

    void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
            if (type != XmlPullParser.START_TAG) {
                continue;
            }
            final String name = parser.getName();
            if (TAG_REQUEST_FOCUS.equals(name)) {
              ......
            } else if (TAG_TAG.equals(name)) {
              ......
            } else {
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                //递归创建子View
                rInflateChildren(parser, view, attrs, true);
                viewGroup.addView(view, params);
            }
        }
        ......
    }

首次调用 parent 参数接收的就是 temp,xml布局的根View,看rInflate()方法时先不考虑<merge> <include>等其他标签,先通过一个 while()循环找到temp下面的第一个子View标签的起始位置,之后将进入 else 语句中执行,依然是调用 createViewFromTag()来创建该子View,创建完子View之后又调用了rInflateChildren()形成递归调用,注意:这次第二个参数传的是 view,之后就是递归创建view下面的所有子View了.递归创建完所有子View之后,都是通过addView()的方法添加到对应的父View中去,这样一直到把整个子View树全部创建完成。

包含标签的递归流程

 在上篇文章中一开始将xml解析的时候就遇到了<merge>标签,我们在写xml布局文件的时候是可以加入各种标签的,有些标签我们经常用到,有些可能使用的频率比较低,这些标签在LayoutInflater中都有定义,下面来一一介绍(只讲LayoutInflater中定义的标签)

public abstract class LayoutInflater {
    private static final String TAG_MERGE = "merge";
    private static final String TAG_INCLUDE = "include";
    private static final String TAG_1995 = "blink";
    private static final String TAG_REQUEST_FOCUS = "requestFocus";
    private static final String TAG_TAG = "tag";

"merge标签"

讲 <merge>标签之前先来看一个关于<merge>标签的事例,还是对第一篇的例子做稍微的改动,原来的activity_mainxml的布局内容保持不变,通过LayoutInflater向其中LinearLayout(id为ll) 添加 layout_merge.xml

<?xml version="1.0" encoding="utf-8"?>
<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <TextView
        android:text="测试布局merge------merge"
        android:textColor="@color/red_200"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <!--"merge"必须放在布局根View的位置否则报错:
    layout/layout_merge: <merge /> must be the root element-->
    <!--<merge>
        <TextView
            android:text="测试布局merge&#45;&#45;&#45;&#45;&#45;&#45;merge"
            android:textColor="@color/red_200"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </merge>-->

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        >
        <TextView
            android:text="测试布局merge------merge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <TextView
            android:text="测试布局merge------merge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <TextView
            android:text="测试布局merge------merge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </LinearLayout>
</merge>
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //ConstraintLayout cs = findViewById(R.id.cs);
        LinearLayout ll = findViewById(R.id.ll);
        LayoutInflater.from(this).inflate(R.layout.layout_merge, ll,true); 
    }

最后的效果如下:

 通过上面的事例来总结下 <merge>标签的用法及作用:

1. <merge>标签只能作为xml的根标签,其他位置会报错(见layout_merge.xml中注释)

2. 使用LayoutInflater加载包含<merge>标签的布局时,必须同时满足 root 不为空且 attachToRoot为true

<merge>标签的作用通过源码就可以看得出来,由于第一篇讲过,这里只截取 inflate()方法的包含 "merge" 的代码

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
           ......
            try {
                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 {
                  ......

上面提到的第2点,看抛异常的代码就很清楚了,当解析到布局中包含 <merge>标签后,直接调用了 rInflate()方法去递归创建所有<merge>标签下的子View,再看下参数,第二个参数传的是 root ,这里的root是我们调用LayoutInflater的inflate方法时自己传入的root父容器,这样以来后面递归创建的<merge>标签之下的所有子View的容器将是 root父容器,以上面的事例来时 root 就是 id 为 ll 的LinearLayout,这里<merge>的效果就好比是直接把 layout_merge.xml的布局放到 id 为 ll 的LinearLayout里面,如果不加<merge>标签,那就需要在最外层再添加一个父容器

所以<merge>标签的作用:可以减少一层嵌套,至于为什么只能是根标签后面会有对应源码

"include"标签

<include>标签也是属于这几个标签中比较常用的一个,由于源码较为枯燥,所以先通过一个事例说下 include 的具体用法,有兴趣的可以往后看源码

 由于activity_main.xml的布局和第一篇一样,这里只贴部分,在父容器 ll 中加了一个 include布局(注意:include标签自身也设置了id)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/cs"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/ll"
        android:background="@color/purple_200"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.21">
        <include
            android:id="@+id/include"
            layout="@layout/layout_include"
            />
    </LinearLayout>
    ......
</androidx.constraintlayout.widget.ConstraintLayout>

layout_include.xml (注意点1:最外层父容器设置了 id,下文会讲;注意点2:如果上面的<include>标签本身设置了宽、高,将会覆盖 id 为 linear_include在xml中的宽、高,也就是如果<include>本身设置了layout_width、layout_height,下面xml布局中的对应的宽高属性将会失效!)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linear_include"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="测试include布局"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

 代码很简单,直接通过setContentView()把activity_main.xml显示出来,效果如下:

通过以上事例总结下<include>用法,<include>的用法也比较简单,它恰好和 <merge>的用法相反,使用<include>需要注意的点:

1.  <include> 标签不能作为布局根标签,必须放在某个父容器内

2.  如果<include>标签本身设置了 id,这个id将会覆盖它所引用的layout的最外层View的id

3. 如果<include>标签本身设置了layout_width layout_height,和id的作用效果一样会覆盖它引用的layout的最外层View的宽、高

上面第 2 点有点绕,直接通过上面的例子就好理解了,activity_main.xml布局中 id为ll的LinearLayout里嵌套了一个<include>标签,这个<include>标签本身有一个id:"include",而这个<include>所引用的布局 layout_include.xml 的最外层View是个Linear Layout也设置了一个id: linear_include,此时layout_include.xml中的LinearLayout 的 id 将会被 <include>标签的id "include"覆盖,也就是如果我们要通过findViewById()找到它,传的id值必须是 R.id.include,否则报错

 接下来看下解析 <include>的源码,比较枯燥,不想了解的这里可以跳过,其实处理tag标签的逻辑都在rInflate()方法中,这次只看处理标签的逻辑

void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
            if (type != XmlPullParser.START_TAG) {
                continue;
            }
            final String name = parser.getName();
            if (TAG_REQUEST_FOCUS.equals(name)) {
                pendingRequestFocus = true;
                consumeChildElements(parser);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }//解析 <include> 标签
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else {
               ......
            }
        }
        ......
    }

<include>标签的解析都在 parseInclude() 方法中

private void parseInclude(XmlPullParser parser, Context context, View parent,
            AttributeSet attrs) throws XmlPullParserException, IOException {
        int type;
        if (!(parent instanceof ViewGroup)) {//<include>必须放在一个父容器里
            throw new InflateException("<include /> can only be used inside of a ViewGroup");
        }
        ......
        if (precompiled == null) {//注意:childParser是<include>标签引用的layoutId所对应的xml解析器
            final XmlResourceParser childParser = context.getResources().getLayout(layout);
            try {//注意:childAttrs是是<include>标签引用的layoutId所对应的属性集合
                final AttributeSet childAttrs = Xml.asAttributeSet(childParser);
                while ((type = childParser.next()) != XmlPullParser.START_TAG &&
                    type != XmlPullParser.END_DOCUMENT) {
                    // Empty.
                }
                ......
                final String childName = childParser.getName();
                if (TAG_MERGE.equals(childName)) {
                    rInflate(childParser, parent, context, childAttrs, false);
                } else {
                    final View view = createViewFromTag(parent, childName,
                        context, childAttrs, hasThemeOverride);
                    final ViewGroup group = (ViewGroup) parent;

                    final TypedArray a = context.obtainStyledAttributes(
                        attrs, R.styleable.Include);//注意这里获取的是<include>标签的id
                    final int id = a.getResourceId(R.styleable.Include_id, View.NO_ID);
                    final int visibility = a.getInt(R.styleable.Include_visibility, -1);
                    a.recycle();
                    ViewGroup.LayoutParams params = null;
                    try {//如果<include>标签本身没有设置宽、高这里会抛出异常
                        params = group.generateLayoutParams(attrs);
                    } catch (RuntimeException e) {
                        // Ignore, just fail over to child attrs.
                    }
                    if (params == null) {//如果<include>标签本身没有设置宽、高,将会使用View在xml布局中的宽、高值
                        params = group.generateLayoutParams(childAttrs);
                    }
                    view.setLayoutParams(params);
                    rInflateChildren(childParser, view, childAttrs, true);
                    if (id != View.NO_ID) {
                        view.setId(id);//把<include>标签的id覆盖View原有的id
                    }
                    ......
                    group.addView(view);
                }
            } finally {
                childParser.close();
            }
        }
        LayoutInflater.consumeChildElements(parser);
    }

解析 <include> 标签时,<include>标签所引用的布局文件最外层View布局参数的设置需要注意下:

1.LayoutParams的设置    2. id值的设置  这些在源码中已经有相应的注释

"blink"标签

这个标签可能我们开发中用的少一些,看它的命名就能大概知道它的效果,"blink"是眨眼、闪烁的意思,是的"blink"标签就是实现了这个一个效果,源码实现也比较简单,直接创建了一个BlinkLayout布局,其实就是一个自定义的FrameLayout

public final View tryCreateView(@Nullable View parent, @NonNull String name,
        @NonNull Context context,
        @NonNull AttributeSet attrs) {
        if (name.equals(TAG_1995)) {
            // Let's party like it's 1995!
            return new BlinkLayout(context, attrs);
        }
        ......
    }

这里的TAG_1995 就是"blink",废话不多说了,直接看下实现代码及效果,直接在Activity中通过setContentView显示就可以了,

layout_tag_blink.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <blink
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="测试blink"
            android:textSize="30sp"
            android:textColor="@color/red_200"
            />
    </blink>

</LinearLayout>

 "requestFocus"标签

这个标签实现也比较简单,是用来获取焦点的,一般用到EditText上,我们可以通过加<requestFocus/>标签来指定哪个View优先获取到焦点

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:hint="第一个"
        android:textSize="20sp"
        android:layout_height="50dp"
        android:layout_width="match_parent"/>

    <EditText
        android:hint="第二个"
        android:layout_marginTop="15dp"
        android:textSize="20sp"
        android:layout_height="50dp"
        android:layout_width="match_parent"/>

    <EditText
        android:hint="第三个"
        android:textSize="20sp"
        android:layout_height="50dp"
        android:layout_width="match_parent">
        <requestFocus/>
    </EditText>

</LinearLayout>

上面布局页面有多个EditText,第三个EditText添加了 <requestFocus/>标签,所以它会优先获取到焦点

"tag"标签

这个标签的作用就是setTag,getTag的作用,只不过我们平时用的多的是在代码中直接使用setTag方法,它的作用就是把数据和一个View绑定起来,当我们要绑定的数据比较多的时候,可以直接在xml中通过添加 <tag>标签的形式实现,"tag"标签的源码也比较简单,在parseViewTag中,不再贴了直接看用法

首先创建 ids.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="linear_tag1" type="id"/>
    <item name="linear_tag2" type="id"/>
    <item name="linear_tag3" type="id"/>

    <item name="textView_tag1" type="id"/>
    <item name="textView_tag2" type="id"/>
    <item name="textView_tag3" type="id"/>
</resources>

实现代码,其中activity_main.xml还是用的之前的例子

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tag);
        LinearLayout ll = findViewById(R.id.ll);
        final LayoutInflater inflater = LayoutInflater.from(this);
        final View view = inflater.inflate(R.layout.layout_tag, ll, false);
        tagTest(view);
        ll.addView(view);
    }
    void tagTest(View view) {
        String linearTag1 = (String) view.getTag(R.id.linear_tag1);
        TextView tv = view.findViewById(R.id.textView);
        String textViewTag3 = (String) tv.getTag(R.id.textView_tag3);
        Log.d("TagActivity_Test", "Tag1: "+linearTag1+"  Tag3: "+textViewTag3);
        //TagActivity_Test  com.github.app_tag   D  Tag1: LinearLayout tag1  Tag3: TextView tag3
    }

layout_tag.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <tag
        android:id="@id/linear_tag1"
        android:value="LinearLayout tag1"
        >
    </tag>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="测试tag标签"
        android:textSize="30sp"
        android:textColor="@color/teal_200"
        android:gravity="center"
        >
        <tag
            android:id="@+id/textView_tag1"
            android:value="TextView tag1"/>
        <tag
            android:id="@+id/textView_tag2"
            android:value="TextView tag2"/>
        <tag
            android:id="@+id/textView_tag3"
            android:value="TextView tag3"/>
    </TextView>

    <tag
        android:id="@id/linear_tag2"
        android:value="LinearLayout tag2"
        />

    <tag
        android:id="@id/linear_tag3"
        android:value="LinearLayout tag3"
        />

    <include layout="@layout/layout_tag_blink"/>
</LinearLayout>

日志打印结果已经在代码中贴出,实现也比较简单,上面的示例都可以直接自己复制粘贴实现,好了到此所有标签都已记录完毕了

LayoutInflater 结合官方文档中的内容,简单介绍一下LayoutInFlater 阅读详情

相关推荐

LayoutInflater 填充器填充布局,布局属性失效问题

无意间看到一个帖子,标题:一个难倒 3年 android开发经验 ” 工程师 ” 的 “bug”,链接地址:http://www.2cto.com/kf/201602/489364.html,所描述的问题就是通过填充器动态添加View对象的时候发现view中的宽高失效,而原帖作者所采用的方式是重新设置布局参数,方法如下代码所示: ll_container=(LinearLayout)

u011573355的博客 2277

Android LayoutInflater 使用详解 View.inflate 的加载原理

志在巅峰的攀登者,不会陶醉在沿途的某个脚印之中,在码农的世界里,优美的应用体验,来源于程序员对细节的处理以及自我要求的境界,年轻人也是忙忙碌碌的码农中一员,每天、每周,都会留下一些脚印,就是这些创作的内容,有一种执着,就是不知为什么,如果你迷茫,不妨来瞅瞅码农的轨迹。 如果你有兴趣 你可以关注一下公众号 biglead 来获取最新的学习资料。 Flutter 从入门 到精通系列文章在这里 系列学习教程在这里 LayoutInflater 是用来将 layout.xml 布局文件添加到指定 V.

代码小疯子 1053

Android Q LayoutInflater布局生成View源码详解

LayoutInflater是Android系统的一个服务,我们可以通过它,把布局文件动态生成View,实现View视图的动态添加。本文将介绍Android Q中LayoutInflater的源码实现,以及inflate的使用注意事项。

卜大爷的博客 2万+

Android View视图绘制流程

===========================第一阶段============================ 任何一个视图都不可能凭空突然出现在屏幕上,它们都是要经过非常科学的绘制流程后才能显示出来的。每一个视图的绘制过程都必须经历三个最主要的阶段,即onMeasure()、onLayout()和onDraw(),下面我们逐个对这三个阶段展开进行探讨。 一. onMeas

xlhb的专栏 603

Android View绘制及事件(二)setContentView()源码,LayoutInflater加载View的过程

前言 通常情况下,我们创建一个Activity时,会通过setContentView来引入布局,将界面视图展现给用户看见。那么,为什么通过setContentView()就能将xml格式的布局文件加载到界面中呢? @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(sa...

csdn_aiyang的博客 1810

安装和使用pandoc

支持 Markdown、DOCX、LaTeX、HTML、PDF、EPUB 等 60+ 种格式 的互相转换

PLANTTHESON的博客 6855

LayoutInflater学习(一)之布局解析

原因分析:通过观察上面第3种情况时的源码就可以知道,当 root 为null时,我们通过LayoutInflater的 inflate 方法加载布局时,在 inflate方法中创建完成xml中最外层的View时,并没有为该View设置布局参数就直接返回了,所以此时 xml 布局中最外层布局的参数LayoutParams是无效的,也就是我们在 xml 中给最外层View设置的宽、高的参数是无效的。LayoutInflater是位于 "android.view" 包下的一个抽象类,同样它也是一个系统级服务。

lollo01的博客 642

CANoe基础讲解01:从零开始使用CANoe轻松搭建你的第一个CAN网络

本文是一篇CANoe软件入门实操指南,逐步演示了如何从零创建并运行一个CAN FD仿真工程。内容包括:启动软件、配置硬件通道与网络、加载DBC数据库、使用CAPL编写仿真节点发送CAN报文,最终启动测量并在Trace窗口中查看通信结果。通过七个清晰步骤,帮助初学者快速掌握CANoe基本操作,完成首个可运行的仿真网络搭建

车载网络小D的博客 1589

View 自定义属性之 LayoutInflater

View 自定义属性之 LayoutInflater 平常开发中,我们避免不了会自定义 view,自定义 view 的时候可以通过 AttributeSet 来获取自定义的相关属性。而怎么样不通过自定义 view,就能实现自定义相关属性呢,那就要使用自定义的 LayoutInflater 了。 原生 LayoutInflater 使用 我们先看看原生的 LayoutInflater 是怎么使用的。...

xyTianZhao 626

小新学习K8s第一天之K8s基础概念

kubernetes是一个可移植,可扩展的开源平台,用于管理容器化工作负载和服务,有助于声明式配置和自动化。它拥有庞大且快速发展的生态系统。kubernetes服务,支持和工具随处可见。作用:用于自动部署,扩展和管理“容器化应用程序”的开源系统。可以理解成k8s是负责自动化运维管理多个容器化程序(比如docker)的集群,是一个生态及其丰富的容器编排框架工具。

pangdongqiqi的博客 1234

GSM的“时间管理大师”:TDMA时隙、突发脉冲与逻辑信道映射实战图解

本文深入解析GSM网络中的TDMA时隙调度与逻辑信道映射技术,揭示2G网络如何通过精密的时间管理和突发脉冲设计实现高效通信。从TDMA帧结构到GMSK调制优化,详细介绍了GSM的工程艺术及其在现代通信中的延续价值。

weixin_30631587的博客 517

android View的布局宽高之LayoutInflater函数详解

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" >

weiersyuan的专栏 8791

【音视频处理】MP4、FLV、HLS适用范围,在线视频播放哪个更好

本期我们讨论在线点播的视频格式,对比这些视频格式的优劣以及原因 1、封装格式的作用 2、MP4 3、FLV 4、HLS

池鱼 - YiiGaa 2万+

LinearLayout详解三:LayoutInflater创建View过程分析

这就是inflate的作用,他就是用来解析xml并显示到屏幕的,至于解析的代码我这边就不多做阐述了,毕竟已经超越了我们的主题太远。我们还是看inflate是如何给解析的xml分配内存,并添加到view上的吧!

kyson 1934

手搓UDS Bootloader|全网独家复现0x10诊断会话控制、详解会话跳转规则与S3超时机制、助力ECU在线刷写、固件迭代、车规安全升级落地

在车载UDS诊断(ISO 14229)与Bootloader固件升级架构中,0x10诊断会话控制服务是所有高级诊断、固件刷写功能的前置核心与权限管控入口,属于UDS基础必实现服务。车载ECU通过分级会话模式,隔离常规故障诊断、高级标定、固件重编程等高、低权限操作,从协议层面保障车载电控系统的安全性与稳定性。多数嵌入式开发者开发UDS Bootloader时,仅简单实现会话切换报文应答,未吃透会话强制跳转规则、S3安全超时机制、会话权限绑定、APP在线刷写跳转逻辑。

getusushu的博客 471

【踩坑记录】colmap中的相机位姿的坐标系定义及其可视化结果的隐含转换

1 坐标系定义及转换   首先介绍一下世界坐标系和相机坐标系之间的转换,它们之间是存在一个转换关系的。现假设空间中一点X,它在相机坐标系下的坐标是Xcamera,在世界坐标系下的坐标是Xworld。假设它通过R和t实现从相机坐标系到世界坐标系之间的转换: Xworld = RXcamera + t   那么,由上式,我们可以推得从世界坐标系向相机坐标系的转换关系(RT=R-1,所以通常直接使用RT即可): Xcamera = RTXworld - RTt   所以,两个坐标系之间的转换,需要看其具体

zeeq的博客 2万+

View->LayoutInflater

LayoutInflater布局填充器代码

sunshine_guo的博客 1008

Unity音游开发全指南:模板与免费资源高效构建节奏游戏

**粒子特效** | [Universal VFX](https://assetstore.unity.com/packages/vfx/particles/universal-vfx-159182) | 免费视觉特效 || **UI素材** | [Game UI Pack](https://assetstore.unity.com/packages/2d/gui/game-ui-pack-86908) | 现代风格UI元素 |**音游开发的黄金法则**:完美的节奏游戏是音乐与游戏的和谐统一。

Loving_enjoy的博客 737

获取View实例——LayoutInflater

文章来自https://github.com/NieJianJian/AndroidNotes,内容将持续更新,欢迎star。 1. LayoutInflater使用场景 LayoutInflater我们都用到过,比如在RecyclerView中加载一个View: public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mConte

聂建jian的专栏 1214

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

LayoutInflater如何加载布局?

对于有一定Android开发经验的同学来说,一定使用过LayoutInflater.inflater()来加载布局文件,但并不一定去深究过它的原理,比如 1.LayoutInflater为什么可以加载layout文件? 2.加载layout文件之后,又是怎么变成供我们使用的View的? 3.我们定义View的时候,如果需要在布局中使用,则必须实现带AttributeSet参数的构造方法,这又是为什么

javine的专栏 1603

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

动态设置布局LayoutInflater

动态设置布局LayoutInflater

随意而然的专栏 1417

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

android layoutinflater 高度,从LayoutInflater.inflate看View的创建过程

从LayoutInflater.inflate看View的创建过程背景:在Activity中,我们通过在onCreate方法中调用setContentView传入一个Layout的资源id就可以完成布局的创建,该方法最终会调用到PhoneWindow的setContentView方法,这个方法里面有这样一行代码:mLayoutInflater.inflate(layoutResID, mConte...

weixin_28958239的博客 344

Android 中LayoutInflater(布局加载器)系列博文说明

关于LayoutInflater的详解系列博文

余杭探险家 6064

View.inflate和LayoutInflater的inflate方法区别

平时ListView加载item中,adapter的getView方法中,我们经常用到: LayoutInflater.from(mContext).inflate(R.layout.it ,parent,false); 这样的方法来加载布局xml,平时一直就是这么用的,也没什么疑问。今天网上看了个自定义布局的源码,自定义布局中加载布局xml用的View.inflate方法: public cl

渴望飞翔的猪 1万+

探秘 Android 中的 LayoutInflater 布局加载原理

LayoutInflater 在 Android 布局加载过程中扮演着重要的角色。它通过解析 XML 文件、创建 View 对象、建立层级关系等步骤,将我们在 XML 中定义的布局转换为可以在屏幕上显示的 View 对象。了解 LayoutInflater 的布局加载原理,有助于我们更好地进行 Android 应用的 UI 开发,同时也可以帮助我们采取有效的优化措施,提高应用的性能和用户体验。希望通过今天的介绍,你对 LayoutInflater 有了更深入的认识。

585

Android--LayoutInflater

在 Android 应用中,界面是通过布局文件(通常是 XML 文件)来定义的。这些布局文件描述了界面的结构和外观,包括各种控件和它们的属性。但是,为了在应用运行时使用这些布局,我们需要将它们从 XML 文件转换成 Java 或 Kotlin 代码中的View对象。这就是的作用所在。

bugyinyin的博客 1173
上一篇: LayoutInflater学习(一)之布局解析
lollo01
博客等级 码龄10年 5粉丝 31原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值