为我的片段制作可重用xml布局的正确方法是什么



所以我有5个不同的片段,它们将具有5个不同业务逻辑。但这5个片段实际上有相同的视图/小部件。每个片段只有一个回收器视图和一个进度条。我想让它更简单,我想避免制作5个xml文件,每个xml文件都包含一个回收器视图和一个进度条。

我有两种方法。

第一种方法。我制作了一个xml文件,称之为widgets.xml,其中将包含回收器视图和进度条。然后我将向所有5个片段布局xml注入CCD_ 2。因此,对于每个片段,我仍然有5个布局xml,但xml很简单,就像这个一样

<?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/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.BFragment" >
<include
layout="@layout/widgets"
/>
</androidx.constraintlayout.widget.ConstraintLayout>

第二种方法。我只制作了一个xml,它将用于我的所有5个片段。所以我只是在onCreate视图中更改inflate中的布局

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setUpRemoteConfigDataForThisFragment()
return inflater.inflate(R.layout.fragment_reusable, container, false)
}

哪种方法更好?还是有更好的方法?

我倾向于选择第二种方法,但我担心tools:context约束布局属性(根(。如果我只制作一个,那么我的所有片段都只有一个上下文。可以吗?

<?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/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.BFragment" > <---- I mean this context
// child views here
</androidx.constraintlayout.widget.ConstraintLayout>

使用recyclerView和进度条只创建一个xml,然后根据需要填充任意多的片段。它不会造成任何混乱。

最新更新