使用相同片段的性能标签布局和Viewpager效果不佳

时间:2018-08-16 13:26:46

标签: android-fragments android-viewpager android-tablayout

我有一份购买物品的清单,我按状态(全部,已取消,已完成)划分它们。 我将TabLayoutViewpager结合使用,并将RecyclerViewcardView结合使用。

因此,我对所有选项卡使用相同的Fragment,因为布局和列表相同,所以我只是根据特定位置更改针对不同状态的查询。

我的问题是,由于我放置了这三个标签,因此加载页面所需的时间太长。大约有三倍的时间(我认为是因为它加载了列表和页面3次)。

因此,我在viewPager.setOffscreenPageLimit(3)的onCreate上尝试了Activity。它可以正确加载所有数据,但是仍然需要太长时间。

我尝试从片段中添加onCreateView

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser && isResumed()) {
        carregaPedidos(position);
    }
}

我还添加了自己的onCreateView

if (getUserVisibleHint()) {
    carregaPedidos(position);
}

但是,以上两者都仅使选项卡1加载。标签2和3变成空白。

我只是想像以前一样快地加载它。或者也许让setUserVisibleHint()工作。

我想知道是否应该为每个Fragment创建3个文件,即使它们具有相同的内容。

我在setUserVisibleHint上做错什么了吗?

编辑:每当我单击每个选项卡时,它都会调用onActivityCreated,而当我第一次打开该页面时,它会被调用两次。

遵循我的代码:

PS:Pedidos是我所用语言中的商品

活动:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meus_pedidos);

        ViewPager viewPager = findViewById(R.id.pager);
        PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), this);
        viewPager.setAdapter(pagerAdapter);
        //viewPager.setOffscreenPageLimit(3);

        TabLayout tabLayout = findViewById(R.id.tablayout);
        tabLayout.setupWithViewPager(viewPager);
    }

    class PagerAdapter extends FragmentPagerAdapter {

        String tabTitles[] = new String[] { "All", "Canceled", "Completed" };
        Context context;

        public PagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }
        @Override
        public int getCount() {
            return tabTitles.length;
        }
        @Override
        public Fragment getItem(int position) {
            return MeusPedidosFragment.newInstance(0,position);
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return tabTitles[position];
        }
    }
}

片段:

public static MeusPedidosFragment newInstance(int tipo, int position){
        Bundle args = new Bundle();
        args.putInt("tipo", tipo);
        args.putInt("position", position);
        MeusPedidosFragment meusPedidosFragment = new MeusPedidosFragment();
        meusPedidosFragment.setArguments(args);
        return  meusPedidosFragment;
    }

    @Override
    public void onCreate(Bundle saveInstanceState){
        super.onCreate(saveInstanceState);
        if(getArguments() != null){
            this.tipo = getArguments().getInt("tipo");
            this.position = getArguments().getInt("position");
            this.pedidos = new ArrayList<>();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (getUserVisibleHint()) {
            loadItems(position);
        }
        View view = inflater.inflate(R.layout.fragment_meus_pedidos, container, false);

        refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.meus_pedidos_layout_swipe_to_refresh);

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(new PedidoAdapter(getContext(), pedidos, onClickPedido()));
        recyclerView.setHasFixedSize(true);
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isResumed()) {
            loadItems(position);
        }
    }

    private SwipeRefreshLayout.OnRefreshListener onRefreshListener(){
        return new SwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                updateMyItems();
            }
        };
    }

    private void updateMyItems() {
        changeCount = 0;
        new Thread(){
            @Override
            public void run(){
                try {
                    //Check if returned something new from database to update list
                    changeCount = PedidoService.obterPedidosPorLastSync(getContext());
                    if (changeCount > 0){
                        if (getUserVisibleHint()) {
                            loadItems(position);
                        }
                    }
                } catch (Exception e) {
                }

                getActivity().runOnUiThread(new Runnable(){
                    @Override
                    public void run(){
                        if(changeCount == 0){
                            snack(recyclerView.getRootView(),getString(R.string.nenhuma_atualizacao_disponivel));
                        }else{
                            recyclerView.setAdapter(new PedidoAdapter(getContext(), pedidos, onClickPedido()));
                        }
                        refreshLayout.setRefreshing(false);
                    }
                });
            }
        }.start();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle b){
        super.onActivityCreated(b);
        taskPedidos();
    }

    private void taskPedidos(){
        dialog = ProgressDialog.show(getActivity(), getString(R.string.meus_pedidos_titulo_progresso),
                getString(R.string.mensagem_por_favor_aguarde),false, true);

        new Thread(){
            @Override
            public void run() {
                try {
                    if (getUserVisibleHint()) {
                        loadItems(position);
                    }
                    //Update a list of items na UI Thread
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(pedidosList != null){
                                snack(recyclerView.getRootView(),getString(R.string.meus_pedidos_erro_download_inicial));
                            }else {
                                recyclerView.setAdapter(new PedidoAdapter(getContext(), pedidos, onClickPedido()));
                            }
                        }
                    });
                } catch (Exception e) {
                }finally {
                }
            }
        }.start();
    }

    public void loadItems(int position) {
        String where = "";

        if (position == 1) {
            where = "WHERE pi.setor IN ('COMPLETED')";
        } else if (position == 3) {
            where = "WHERE pi.setor IN ('CANCELED')";
        }
        pedidos = new PedidoDB(getContext()).obterPedidos(where);
    }

0 个答案:

没有答案