Fragment的根布局可不可以使用merge標(biāo)簽?

先看這段xml,它可以作為我們Fragment的根布局嗎?

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
        android:id="@+id/tv_text"
        android:layout_width="200dp"
        android:layout_gravity="right"
        android:layout_height="100dp"
        android:gravity="center"
        android:text="This is a merge fragment!" />
</merge>

我們再來看一下LayoutInflater的源碼:

 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;
            try {
                advanceToRootNode(parser);
                final String name = parser.getName();
                ...
                if (TAG_MERGE.equals(name)) {
                    // 關(guān)鍵看這段代碼
                    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 {
                    ...
                }
            } catch (Exception e) {
               ...
            } finally {
               ...
            }
            return result;
        }
    }

只看關(guān)鍵代碼,發(fā)現(xiàn)其實應(yīng)該是可以的,只需要root!=null && attachToRoot==true就可以了。
下面具體看看Fragment如何去實現(xiàn):

/**
 * @author xiaobocui
 * @date 2020/5/8
 */
class TestFragment : Fragment() {
    companion object {
        fun newInstance(): TestFragment {
            return TestFragment()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        inflater.inflate(R.layout.fragment_test, container, true)
        return super.onCreateView(inflater, container, savedInstanceState)
        // 或者 return null 也行
    }
}

這里有個注意事項,如果根標(biāo)簽是merge那么onCreateView方法的返回值就不能再返回view了,否則會添加多次,而拋出異常。
其實在inflater.inflate(R.layout.fragment_test, container, true)這段代碼中就已經(jīng)將merge的標(biāo)簽的布局添加到container里面去了。
大功告成,這樣操作,F(xiàn)ragment的根布局就可以使用merge標(biāo)簽了?。?!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容