Java 如何使用RecyclerView更新片段数据?
我有一个Java 如何使用RecyclerView更新片段数据?,java,android,android-recyclerview,fragment,Java,Android,Android Recyclerview,Fragment,我有一个ViewPager和12个片段。我需要从API获取数据,并在滚动时更新片段。我如何更新片段的内容,只有一个片段更新了12页 我的片段布局片段\u项: <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/content" android:layout_widt
ViewPager
和12个片段。我需要从API获取数据,并在滚动时更新片段。我如何更新片段的内容,只有一个片段更新了12页
我的片段布局片段\u项:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/surface">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/khaire"
android:gravity="center"
android:text="Overal Working Hour"
android:textColor="@color/colorPrimary"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:gravity="center"
android:padding="15dp"
android:text="January"
android:textColor="@color/white"
android:textSize="20sp"
android:textStyle="bold" />
我的幻灯片放映课:
public class SliderFragment extends Fragment {
Toolbar toolbar;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_item,container,false);
return rootView;
}
现在我想有相同的片段,而滚动页面,但与不同的文本我怎么能做到这一点。。。如果可能的话,还可以使用RecyclerView
。您可以使用公共抽象updateView()创建一个新类(updatefragment)扩展片段的代码>
通过扩展updatefragment
而不是Fragment来创建您的SliderFragment
在onCreateView()
中的SliderFragment
中,在最后调用updateView()
时
在您的SliderFragment
中编写一个覆盖方法,用于更新您需要更新的内容(您想在UI上显示的任何内容)
调整screenAdapter
返回并获取updateingfragment
,而不是片段
现在,每当调用片段onCreateView
时,它们的所有UI数据都会更新,如果您创建一个SliderFragments
列表,并将其传递到适配器中,而不是创建新的,您只需在该列表上运行for循环并调用updateView()
对于每个片段。用一些代码描述更多关于这个问题的信息。使用Singleton类解决这个问题。这是对我有效的最佳解决方案。您可以在Fragment
中重写此方法,这样当用户看到它时,只有它才会更新@override public void setMenuVisibility(boolean menuVisible){super.setMenuVisibility(menuVisible);if(menuVisible){//code to update fragment}}
你能举个简单的例子吗
public class SliderFragment extends Fragment {
Toolbar toolbar;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_item,container,false);
return rootView;
}