如何使用回收器视图更新片段数据?



我有一个 12fragmentsViewPager。我需要从 API 获取数据并在滚动时更新片段。如何更新片段的内容,仅更新 12 页的一个片段?

我的片段布局fragment_item:

<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 MainActivity extends AppCompatActivity {
private static final int num_pages = 12;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);  
mPager = findViewById(R.id.pager);
mPagerAdapter = new ScreenAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
private class ScreenAdapter extends FragmentStatePagerAdapter {
public ScreenAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
return new SliderFragment();
}
@Override
public int getCount() {
return num_pages;
}
}

我的幻灯片片段类:

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

您可以使用扩展 Fragment 的公共抽象updateView();创建一个新类(更新片段(。

通过扩展UpdatingFragment而不是片段来创建SliderFragment

SliderFragmentonCreateView()末尾调用updateView().

SliderFragment中为需要更新的内容(要在 UI 上显示的任何内容(编写覆盖方法

调整您的screenAdapter以返回并获取UpdatingFragment而不是片段。

现在,每当调用片段onCreateView时,它们的所有 UI 数据都会更新,如果您创建一个SliderFragments列表并将其传递到适配器中而不是创建新,您只需在该列表上运行 for 循环并为每个片段调用updateView()

最新更新