先看這段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>
我們?cè)賮?lái)看一下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)其實(shí)應(yīng)該是可以的线脚,只需要root!=null && attachToRoot==true就可以了。
下面具體看看Fragment如何去實(shí)現(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 也行
}
}
這里有個(gè)注意事項(xiàng)叫榕,如果根標(biāo)簽是merge那么onCreateView方法的返回值就不能再返回view了浑侥,否則會(huì)添加多次,而拋出異常晰绎。
其實(shí)在inflater.inflate(R.layout.fragment_test, container, true)這段代碼中就已經(jīng)將merge的標(biāo)簽的布局添加到container里面去了寓落。
大功告成,這樣操作荞下,F(xiàn)ragment的根布局就可以使用merge標(biāo)簽了A嫜 J贩伞!