当前位置:   article > 正文

ViewPager动态添加或删除Fragment刷新空白问题处理,及Fragment数据传递简介_viewpager+fragment动态增加,删除页面

viewpager+fragment动态增加,删除页面

很久没更博客了,因为自己前段时间一直在独立开发项目、、、但这不能成为懒惰的理由,自省3秒···  好了废话不多说,开始撸码

(以后都会采取先Java展示,后kotlin展示形式,小伙伴们可以各取所需)

之前一直都是很基础的固定Fragment个数与ViewPager搭配使用,在项目中要求动态添加Fragment展示界面,但是却遇到了刷新空白,或者刷新不完全的问题出现,借此自写个demo以供参考

效果入下:

解释下为什么会刷新失败:原因是Fragment在adapter中会形成缓存,在每次创建前都会去对比一下此Fragment是否存在,这就是造成刷新不是我们预想的情况出现

步骤如下:

1、新建类并继承Fragment,接受数据完善布局

2、创建类并继承 FragmentStatePagerAdapter ,重写其内部方法 ,并重写getItemPosition()将返回值设置为PagerAdapter.POSITION_NONE(此处解决刷新问题)

3、程序中实现数据源、viewpager及其adapter配置即可

代码如下:

1、新建类并继承Fragment,接受数据完善布局

  1. package com.leixiansheng.test;
  2. import android.os.Bundle;
  3. import android.support.annotation.Nullable;
  4. import android.support.v4.app.Fragment;
  5. import android.view.LayoutInflater;
  6. import android.view.View;
  7. import android.view.ViewGroup;
  8. import android.widget.TextView;
  9. /**
  10. * Created by Leixiansheng on 2018/12/10.
  11. */
  12. public class MyFragment extends Fragment {
  13. public static Fragment newInstance(String content) {
  14. MyFragment fragment = new MyFragment();
  15. Bundle bundle = new Bundle();
  16. bundle.putString("content", content);
  17. fragment.setArguments(bundle);
  18. return fragment;
  19. }
  20. @Nullable
  21. @Override
  22. public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
  23. String content = getArguments().getString("content");
  24. View view = inflater.inflate(R.layout.fragment_base, container, false);
  25. TextView textView = (TextView) view.findViewById(R.id.tvContent);
  26. textView.setText(content);
  27. return view;
  28. }
  29. }
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <TextView
  6. android:id="@+id/tvContent"
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:layout_centerInParent="true"
  10. android:textSize="20sp"
  11. android:textColor="@color/colorAccent"/>
  12. </RelativeLayout>

2、创建类并继承 FragmentStatePagerAdapter ,重写其内部方法

3、程序中实现数据源、viewpager及其adapter配置即可

  1. package com.leixiansheng.test;
  2. import android.support.v4.app.Fragment;
  3. import android.support.v4.app.FragmentManager;
  4. import android.support.v4.app.FragmentStatePagerAdapter;
  5. import android.support.v4.view.PagerAdapter;
  6. import android.support.v4.view.ViewPager;
  7. import android.support.v7.app.AppCompatActivity;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. import android.widget.Button;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. public class MainActivity extends AppCompatActivity implements View.OnClickListener{
  14. private List<String> contents = new ArrayList<>();
  15. private MyFragmentPagerAdapter adapter;
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_main);
  20. contents.add("one");
  21. contents.add("two");
  22. contents.add("three");
  23. ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
  24. Button add = (Button) findViewById(R.id.btnAdd);
  25. Button delete = (Button) findViewById(R.id.btnDelete);
  26. adapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
  27. viewPager.setAdapter(adapter);
  28. add.setOnClickListener(this);
  29. delete.setOnClickListener(this);
  30. }
  31. @Override
  32. public void onClick(View v) {
  33. switch (v.getId()) {
  34. case R.id.btnAdd:
  35. contents.add("add");
  36. adapter.notifyDataSetChanged();
  37. break;
  38. case R.id.btnDelete:
  39. if (contents.size() > 0) {
  40. contents.remove(contents.size() - 1);
  41. adapter.notifyDataSetChanged();
  42. }
  43. break;
  44. default:
  45. break;
  46. }
  47. }
  48. class MyFragmentPagerAdapter extends FragmentStatePagerAdapter{
  49. private MyFragmentPagerAdapter(FragmentManager fm) {
  50. super(fm);
  51. }
  52. @Override
  53. public Fragment getItem(int position) {
  54. return MyFragment.newInstance(contents.get(position));
  55. }
  56. @Override
  57. public int getCount() {
  58. return contents.size();
  59. }
  60. @Override
  61. public int getItemPosition(Object object) {
  62. return PagerAdapter.POSITION_NONE;
  63. }
  64. }
  65. }

Kotlin代码如下(与国际接轨嘛,啊哈哈)

  1. package com.leixiansheng.kotlintest
  2. import android.os.Bundle
  3. import android.support.v4.app.Fragment
  4. import android.view.LayoutInflater
  5. import android.view.View
  6. import android.view.ViewGroup
  7. import android.widget.TextView
  8. import kotlinx.android.synthetic.main.fragment_base.view.*
  9. /**
  10. * Created by Leixiansheng on 2018/11/23.
  11. */
  12. class MyFragment : Fragment() {
  13. fun newInstance(text:String):MyFragment{
  14. val fragment = MyFragment()
  15. val bundle = Bundle()
  16. bundle.putString("content", text)
  17. fragment.arguments = bundle
  18. return fragment
  19. }
  20. override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
  21. val content = arguments.getString("content")
  22. val view = inflater!!.inflate(R.layout.fragment_base, container, false)
  23. val tvContent: TextView = view.tvContent
  24. tvContent.text = content
  25. return view
  26. }
  27. }
  1. package com.leixiansheng.kotlintest
  2. import android.support.v7.app.AppCompatActivity
  3. import android.os.Bundle
  4. import android.support.v4.app.Fragment
  5. import android.support.v4.app.FragmentManager
  6. import android.support.v4.app.FragmentStatePagerAdapter
  7. import android.support.v4.view.PagerAdapter
  8. import kotlinx.android.synthetic.main.activity_main.*
  9. class MainActivity : AppCompatActivity() {
  10. val list = mutableListOf<String>("one", "two", "three")
  11. override fun onCreate(savedInstanceState: Bundle?) {
  12. super.onCreate(savedInstanceState)
  13. setContentView(R.layout.activity_main)
  14. val adapter = MyFragmentPagerAdapter(supportFragmentManager, list)
  15. viewPager.adapter = adapter
  16. add.setOnClickListener {
  17. list.add("add")
  18. adapter.notifyDataSetChanged()
  19. }
  20. delete.setOnClickListener {
  21. if (list.size > 0) {
  22. list.removeAt(list.size-1)
  23. adapter.notifyDataSetChanged()
  24. }
  25. }
  26. }
  27. class MyFragmentPagerAdapter(fm:FragmentManager,val list: List<String>) : FragmentStatePagerAdapter(fm){
  28. /**
  29. * Return the Fragment associated with a specified position.
  30. */
  31. override fun getItem(position: Int): Fragment {
  32. return MyFragment().newInstance(list[position])
  33. }
  34. /**
  35. * Return the number of views available.
  36. */
  37. override fun getCount(): Int {
  38. return list.size
  39. }
  40. /**
  41. * 必须重写此方法才能完全刷新
  42. */
  43. override fun getItemPosition(`object`: Any?): Int {
  44. return PagerAdapter.POSITION_NONE
  45. }
  46. }
  47. }

还有一种处理情况继承的是  FragmentPagerAdapter时:

在Adapter中添加一个方法,手动移除存在的Fragment

  1. private void setFragments(List<OverlapFragment> fragments) {
  2. FragmentManager fm = getFragmentManager();
  3. if (mFragments != null) {
  4. FragmentTransaction ft = fm.beginTransaction();
  5. for (Fragment f : fragments) {
  6. ft.remove(f);
  7. }
  8. ft.commit();
  9. ft = null;
  10. fm.executePendingTransactions();
  11. }
  12. mFragments = fragments;
  13. notifyDataSetChanged();
  14. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/174878
推荐阅读
相关标签
  

闽ICP备14008679号