所以我有5个不同的片段,将有5个不同的业务逻辑。但实际上有5个片段具有相同的视图/小部件。每个片段只有一个回收站视图和进度条。并且我想使其更简单,并且希望避免制作5个xml文件,并且每个xml文件都包含一个回收站视图和一个进度条。
我有2种方法。
第一种方法。我制作了一个xml文件,命名为widgets.xml
,它将包含回收站视图和进度栏。然后将widgets.xml
插入所有5个片段布局xml。因此我仍然为每个片段保留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>
第二种方法。我只制作一个可用于我所有5个片段的xml。所以我只是在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>
所以我有5个不同的片段,将有5个不同的业务逻辑。但实际上有5个片段具有相同的视图/小部件。每个片段只有一个回收站视图和进度条。 ...
仅使用recyclerView和进度条创建一个xml,然后根据需要填充尽可能多的片段。它不会造成任何混乱。