ViewPager结合Fragmen使用,页面切换时,Fragment中的listView没有加载

在我们开发的过程中可能会遇到类似需求,我们需要做一个左右滑动的tab导航,这个时候有些朋友可能会想到viewpager和fragment的结合来实现这个功能;

当然实现的方法不单单着一种。我们这个随笔讨论的是这种方式实现的效果、现在假如我们选中了服务这个列,服务列下有一个listview用来展示数据。然后滑动到第二个评价的fragment再到第三个商家fragment,或者是直接到最后一个fragment,然后再回来第一个fragment,我们会发现fragment刷新了一下。这里fragment重新create了,这个时候会发现listview的数据不对了。但我们并没有进行刷新操作!这个时候我们只需要重写ViewPager适配器的:

@Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //super.destroyItem(container, position, object);
        }

然后把super.destroyItem(container, position, object);注释掉,让fragment一直存在着。这样你再次运行会发现刚刚那个问题已经解决了。

如:

/**
     * ViewPager适配器
     *
     * @author xl
     */
    class MyFragmentViewPager extends FragmentPagerAdapter {

        public MyFragmentViewPager(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return m_listFragment.get(position);
        }

        @Override
        public int getCount() {
            return m_listFragment.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //super.destroyItem(container, position, object);
        }
    }

示例:

/**
 * 主页
 * Created by xl on 2019/10/9.
 */
public class HomeActivity extends FragmentActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {

    private final static String TAG = HomeActivity.class.getSimpleName();
    private ViewPager m_viewPager;
    private NavImageBtn[] m_navTabs = new NavImageBtn[4];
    private List<Fragment> m_listFragment;
    private MyFragmentViewPager m_viewPagerAdapter;
    private MonitorFragment m_fragMonitor;
    private MapFragment m_fragMap;
    private FaultFragment m_fragFault;
    private UserFragment m_fragUser;
    private int m_iCurFragment = 0;
    private String m_strVerName = "0.0.0"; // 例如1.0.3

    private final int[] m_iArrTabResid = new int[]{
            R.string.t_index_monitoring, R.string.t_list_map_monitor, R.string.t_index_breakdown, R.string.t_index_user
    };
    private final int[] m_iArrDefResid = new int[]{
            R.drawable.index_monitor_p, R.drawable.tab_map, R.drawable.index_fault_p, R.drawable.index_info_p
    };
    private final int[] m_iArrSelResid = new int[]{
            R.drawable.index_monitor, R.drawable.tab_map_p, R.drawable.index_fault, R.drawable.index_info
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        findView();
        init();
    }

    private void findView() {
        m_viewPager = (ViewPager) this.findViewById(R.id.viewpager);
        m_navTabs[0] = (NavImageBtn) this.findViewById(R.id.tab1);
        m_navTabs[1] = (NavImageBtn) this.findViewById(R.id.tab2);
        m_navTabs[2] = (NavImageBtn) this.findViewById(R.id.tab3);
        m_navTabs[3] = (NavImageBtn) this.findViewById(R.id.tab4);
    }

    private void init() {
        // 将activity放入堆栈
        AppManager.getAppManager().addActivity(this);
        //初始化fragment集合
        initFragmentList();
        //初始化viewpager
        m_viewPagerAdapter = new MyFragmentViewPager(getSupportFragmentManager());
        m_viewPager.setAdapter(m_viewPagerAdapter);
        m_viewPager.setOnPageChangeListener(this);
        //初始化tab
        initTab();
        //默认显示第一页
        setNavBtnStatus(0);
        //判断当前是否是最新版本
        getApkVersion();
    }

    /**
     * 初始化fragment集合
     */
    private void initFragmentList() {
        m_listFragment = new ArrayList<>();
        m_fragMonitor = new MonitorFragment();
        m_fragMap = new MapFragment();
        m_fragFault = new FaultFragment();
        m_fragUser = new UserFragment();
        m_listFragment.add(m_fragMonitor);
        m_listFragment.add(m_fragMap);
        m_listFragment.add(m_fragFault);
        m_listFragment.add(m_fragUser);
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {
    }

    @Override
    public void onPageSelected(int position) {
        setNavBtnStatus(position);
        switch (position) {
            case 0:
                break;
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int i) {
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tab1:
                m_viewPager.setCurrentItem(0, true);
                break;
            case R.id.tab2:
                m_viewPager.setCurrentItem(1, true);
                break;
            case R.id.tab3:
                m_viewPager.setCurrentItem(2, true);
                break;
            case R.id.tab4:
                m_viewPager.setCurrentItem(3, true);
                break;
        }
    }

    /**
     * ViewPager适配器
     *
     * @author xl
     */
    class MyFragmentViewPager extends FragmentPagerAdapter {

        public MyFragmentViewPager(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return m_listFragment.get(position);
        }

        @Override
        public int getCount() {
            return m_listFragment.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //super.destroyItem(container, position, object);
        }
    }

    /**
     * 设置imgbtn
     *
     * @param position
     */
    public void setNavBtnStatus(int position) {
        switch (position) {
            case 0:
                m_navTabs[0].setClickStatus(true);
                m_navTabs[1].setClickStatus(false);
                m_navTabs[2].setClickStatus(false);
                m_navTabs[3].setClickStatus(false);
                break;
            case 1:
                m_navTabs[0].setClickStatus(false);
                m_navTabs[1].setClickStatus(true);
                m_navTabs[2].setClickStatus(false);
                m_navTabs[3].setClickStatus(false);
                break;
            case 2:
                m_navTabs[0].setClickStatus(false);
                m_navTabs[1].setClickStatus(false);
                m_navTabs[2].setClickStatus(true);
                m_navTabs[3].setClickStatus(false);
                break;
            case 3:
                m_navTabs[0].setClickStatus(false);
                m_navTabs[1].setClickStatus(false);
                m_navTabs[2].setClickStatus(false);
                m_navTabs[3].setClickStatus(true);
                break;
            default:
                break;
        }
        m_iCurFragment = position;
    }

    /**
     * 初始化Tab
     */
    private void initTab() {
        for (int i = 0; i < m_navTabs.length; i++) {
            m_navTabs[i].setText(m_iArrTabResid[i]);
            m_navTabs[i].setImageSrc(m_iArrDefResid[i], m_iArrSelResid[i]);
            m_navTabs[i].setOnTabClickListener(this);
        }
    }

    @Override
    public void onBackPressed() {
        AppManager.getAppManager().AppExit(this);
    }

    /**
     * 获取apk版本号
     */
    public void getApkVersion() {
        // 得到软件当前版本号
        try {
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
            m_strVerName = info.versionName; // 软件版本,例如"1.0.3"
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        HttpTask http = new HttpTask(HttpUrl.SOFT_VERSION, HttpPara.SOFT_VERSION, new OnFunHttpCallBack() {
            @Override
            public void OnStart() {
            }

            @Override
            public void OnFinish(String url, String json) {
                MyLogger.i(TAG, json);
                try {
                    JSONObject result = new JSONObject(json);
                    if (url.equals(HttpUrl.SOFT_VERSION)) {
                        if (result.optString("msgCode").equals("0") && result.optString("data").compareTo(m_strVerName) > 0) {
                            updateTip(result.optString("data"));
                        }
                    }
                } catch (Exception e) {
                    MyLogger.e(TAG, e.getMessage());
                }
            }
        });
        http.runGet();
    }

    /**
     * 弹框提示更新
     *
     * @param version
     */
    private void updateTip(final String version) {
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (which == DialogInterface.BUTTON_POSITIVE) { // 确定按键的点击事件
                    softupdate(version);
                } else if (which == DialogInterface.BUTTON_NEGATIVE) { // 取消按键的点击事件
                }
            }
        };
        // 创建提示信息对话框
        int iconId = R.drawable.login_tip;
        String title = getResources().getString(R.string.t_title_info);
        String msg = getResources().getString(R.string.msg_update_tip_h) + version + getResources().getString(R.string.msg_update_tip_l);
        CustomDialog.MessageBox(this, iconId, title, msg, listener, 2);
    }

    /**
     * 下载apk
     *
     * @param version
     */
    private void softupdate(String version) {
        UpdateManager.getInstance().showDownloadDialog(this, version, HttpUrl.SOFT_UPDATE + "?" + HttpPara.SOFT_UPDATE);
    }

    /**
     * 跳转到新的Activity
     *
     * @param aty
     */
    public void enter(Class<? extends Activity> aty, Bundle bundle) {
        Intent intent = new Intent(this, aty);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

}

完!!!

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页