【发布时间】:2018-10-04 04:26:14
【问题描述】:
我有一个 ViewPager 和 12 个 fragments。我需要从 API 获取数据并在滚动时更新片段。如何更新fragment的内容,12页只更新一个fragment?
我的片段布局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;
}
}
我的 SlideFragment 类:
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中覆盖此方法,这样当它对用户可见时,只有它会更新@Override public void setMenuVisibility(boolean menuVisible) { super.setMenuVisibility(menuVisible); if (menuVisible) { //code to update fragment } } -
能否请您提供一个简单的代码示例
标签: java android android-recyclerview fragment