从隐式intent

时间:2017-04-21 22:34:36

标签: android listview android-fragments back-button

我正在构建一个从Web获取数据并将其呈现在ListView中的应用程序。然后,当我点击某个项目时,会打开相应的网页。问题是当我点击后退按钮 - 返回应用程序时 - 数据的获取将重新开始,最终刷新ListView。

我有一个主要活动来控制3个碎片。每个的OnCreate和OnCreateView方法粘贴在下面。

谢谢。

主要活动

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set the content of the activity to use the activity_main.xml layout file
    setContentView(R.layout.activity_main);
    myFragStack = new Stack<Fragment>();
    mn=MainActivity.this;

    this.initialiseTabHost(savedInstanceState);
    if (savedInstanceState != null) {
        // Define a Tab de acordo com o estado salvo
        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
    }
    // Inicializa o ViewPager
    this.intialiseViewPager();

}

EstatisticasFragment

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    setRetainInstance(true);
    // Set the content of the activity to use the activity_main.xml layout file

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    esconderTeclado(this.getActivity());
    rootView = inflater.inflate(R.layout.fragment_estatisticas, container, false);
    loadingIndicator = (ProgressBar) rootView.findViewById(R.id.loading_indicator);
    //FragmentActivity activity = (FragmentActivity) rootView.getContext();
    // Hide loading indicator because the data has been loaded
    hideLoadingIndicator();

    return rootView;
}

Resultados Fragment

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    esconderTeclado(this.getActivity());
    rootView = inflater.inflate(R.layout.fragment_resultados, container, false);

    // Esconder loading indicator porque os dados foram carregados
    View loadingIndicator = rootView.findViewById(R.id.loading_indicator);
    loadingIndicator.setVisibility(View.GONE);

    recordListView = (ListView) rootView.findViewById(R.id.listview_record);
    mEmptyStateTextView = (TextView) rootView.findViewById(R.id.empty_view);
    recordListView.setEmptyView(mEmptyStateTextView);

    // Create a new adapter that takes an empty list of records as input
    mAdapter = new ResultadosRecordAdapter(getActivity(), new ArrayList<Record>());
    setRetainInstance(true);
    // Set the adapter on the {@link ListView}
    // so the list can be populated in the user interface
    recordListView.setAdapter(mAdapter);
    // define Choice mode for multiple  delete
    recordListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    recordListView.setMultiChoiceModeListener(new  AbsListView.MultiChoiceModeListener() {

        @Override
        public boolean  onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
            // TODO  Auto-generated method stub
            return false;
        }


        @Override
        public void  onDestroyActionMode(android.view.ActionMode mode) {
            // TODO  Auto-generated method stub

        }

        @Override
        public boolean  onCreateActionMode(android.view.ActionMode mode, Menu menu) {
            // TODO  Auto-generated method stub
            mode.getMenuInflater().inflate(R.menu.menu_resultados_contextual, menu);
            return true;

        }


        @Override
        public boolean  onActionItemClicked(final android.view.ActionMode mode,
                                            MenuItem item) {
            // TODO  Auto-generated method stub

            switch  (item.getItemId()) {
                case R.id.selectAll:
                    //
                    final int checkedCount  = recordsGlobal.size();
                    // If item  is already selected or checked then remove or
                    // unchecked  and again select all
                    mAdapter.removeSelection();
                    for (int i = 0; i <  checkedCount; i++) {
                        recordListView.setItemChecked(i,   true);
                        //  listviewadapter.toggleSelection(i);
                    }
                    // Set the  CAB title according to total checked items

                    // Calls  toggleSelection method from ListViewAdapter Class

                    // Count no.  of selected item and print it
                    mode.setTitle(checkedCount  + "  Selecionados");
                    return true;
                case R.id.delete:
                    // Add  dialog for confirmation to delete selected item
                    // record.
                    AlertDialog.Builder  builder = new AlertDialog.Builder(
                            getContext());
                    builder.setMessage("Confirmar exclusão do(s) disco(s) selecionado(s)?");

                    builder.setNegativeButton("Não", new  DialogInterface.OnClickListener() {

                        @Override
                        public void  onClick(DialogInterface dialog, int which) {
                            // TODO  Auto-generated method stub

                        }
                    });
                    builder.setPositiveButton("Sim", new  DialogInterface.OnClickListener() {

                        @Override
                        public void  onClick(DialogInterface dialog, int which) {
                            // TODO  Auto-generated method stub
                            SparseBooleanArray selected = mAdapter
                                    .getSelectedIds();
                            for (int i =  (selected.size() - 1); i >= 0; i--) {
                                if  (selected.valueAt(i)) {
                                    Record selecteditem = mAdapter
                                            .getItem(selected.keyAt(i));
                                    // Remove  selected items following the ids
                                    DeletadosFragment.mDeletadosAdapter.add(selecteditem);
                                    DeletadosFragment.recordsDeletadosGlobal.add(selecteditem);
                                    mAdapter.remove(selecteditem);
                                    recordsGlobal.remove(selecteditem);

                                    Double priceSum = 0.0;
                                    for (int j = 0; j < recordsGlobal.size(); j++){
                                        priceSum += recordsGlobal.get(j).getmPrice();
                                        System.out.println("recordsGlobal.get(j).getmPrice(): " + recordsGlobal.get(j).getmPrice());
                                    }
                                    System.out.println("priceSum: " + priceSum + "\nrecordsGlobal.size(): " + recordsGlobal.size());
                                    Double mediaDouble = EstatisticasFragment.fazerMedia(priceSum, recordsGlobal.size());
                                    String media = mediaDouble.toString();

                                    TextView mediaFinal = (TextView) EstatisticasFragment.rootView.findViewById(R.id.textViewMedia);
                                    mediaFinal.setVisibility(View.VISIBLE);
                                    media = QueryUtils.trimPrice(media);
                                    mediaFinal.setText("R$" + media);
                                    mediaFinal.setTextSize(50);
                                    Activity activity = (Activity) EstatisticasFragment.rootView.getContext();
                                    mediaFinal.setTextColor(ContextCompat.getColor(activity, R.color.colorPrice));

                                    int sumOfRecords = recordsGlobal.size();

                                    Double desvioPadrao = EstatisticasFragment.calcularDesvioPadrao(mediaDouble, ResultadosFragment.recordsGlobal);
                                    Double coeficienteVariacao = EstatisticasFragment.calcularcoeficienteDeVariacaoDosRecords(mediaDouble, desvioPadrao);

                                    TextView totalDeRegistros = (TextView) EstatisticasFragment.rootView.findViewById(R.id.textViewTotalRegistros);
                                    String sumOfRecordsString = Integer.toString(sumOfRecords);
                                    totalDeRegistros.setText("Total de Registros: " + sumOfRecordsString +"\nDesvio Padrão: " + desvioPadrao + "\nC.V: " + coeficienteVariacao);
                                    totalDeRegistros.setTextSize(10);
                                    totalDeRegistros.setTextColor(ContextCompat.getColor(EstatisticasFragment.rootView.getContext(), R.color.colorPrice));
                                }
                            }

                            // Close CAB
                            mode.finish();
                            selected.clear();
                            mAdapter.notifyDataSetChanged();
                            mAdapter.notifyDataSetInvalidated();
                            DeletadosFragment.mDeletadosAdapter.notifyDataSetChanged();
                            DeletadosFragment.mDeletadosAdapter.notifyDataSetInvalidated();

                        }
                    });
                    AlertDialog alert =  builder.create();
                    //alert.setIcon(R.drawable.questionicon);// dialog  Icon
                    alert.setTitle("Confirmation"); // dialog  Title
                    alert.show();
                    return true;
                default:
                    return false;
            }

        }

        @Override
        public void  onItemCheckedStateChanged(android.view.ActionMode mode,
                                               int position, long id, boolean checked) {
            // TODO  Auto-generated method stub
            final int checkedCount  = recordListView.getCheckedItemCount();
            // Set the  CAB title according to total checked items
            mode.setTitle(checkedCount  + "  Selecionado(s)");
            // Calls  toggleSelection method from ListViewAdapter Class
            mAdapter.toggleSelection(position);
        }
    });

    recordListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            // Achar o record atual que foi clicado
            Record currentRecord = mAdapter.getItem(position);

            // Converte o URL String em um objeto URI (para passar no construtor de Intent)
            Uri recordUri = Uri.parse(currentRecord.getmPermalink());

            Intent intent = new Intent(Intent.ACTION_VIEW, recordUri);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent);

        }
    });

    /**recordListView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                                                      @Override
                                                      public void onCreateContextMenu(ContextMenu contextMenu, View view,
                                                                                      ContextMenu.ContextMenuInfo contextMenuInfo) {
                                                          contextMenu.add(Menu.NONE, 1, Menu.NONE, "Deletar Registro");
                                                      }
                                                  }

    );**/

    setHasOptionsMenu(true);

    return rootView;

}

DeletadosFragment

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

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

    esconderTeclado(getActivity());

    View rootView = inflater.inflate(R.layout.fragment_deletados, container, false);
    // Hide loading indicator because the data has been loaded
    View loadingIndicator = rootView.findViewById(R.id.loading_indicator_deletados);
    loadingIndicator.setVisibility(View.GONE);

    final ListView recordsDeletadosListView = (ListView) rootView.findViewById(R.id.listview_record_deletados);

    /**
     * TextView that is displayed when the list is empty
     */
    TextView mEmptyStateTextView = (TextView) rootView.findViewById(R.id.empty_view_deletados);

    recordsDeletadosListView.setEmptyView(mEmptyStateTextView);

    // Create a new adapter that takes an empty list of records as input
    mDeletadosAdapter = new DeletadosRecordAdapter(getActivity(), new ArrayList<Record>());

    // Set the adapter on the {@link ListView}
    // so the list can be populated in the user interface
    recordsDeletadosListView.setAdapter(mDeletadosAdapter);
    // define Choice mode for multiple  delete
    recordsDeletadosListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    recordsDeletadosListView.setMultiChoiceModeListener(new  AbsListView.MultiChoiceModeListener() {

        @Override
        public boolean  onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
            // TODO  Auto-generated method stub
            return false;
        }


        @Override
        public void  onDestroyActionMode(android.view.ActionMode mode) {
            // TODO  Auto-generated method stub

        }

        @Override
        public boolean  onCreateActionMode(android.view.ActionMode mode, Menu menu) {
            // TODO  Auto-generated method stub
            mode.getMenuInflater().inflate(R.menu.menu_deletados_contextual, menu);
            return true;

        }

        @Override
        public boolean  onActionItemClicked(final android.view.ActionMode mode,
                                            MenuItem item) {
            // TODO  Auto-generated method stub
            switch  (item.getItemId()) {
                case R.id.selectAll:
                    //
                    final int checkedCount  = recordsDeletadosGlobal.size();
                    // If item  is already selected or checked then remove or
                    // unchecked  and again select all
                    mDeletadosAdapter.removeSelection();
                    for (int i = 0; i <  checkedCount; i++) {
                        recordsDeletadosListView.setItemChecked(i,   true);
                        //  listviewadapter.toggleSelection(i);
                    }
                    // Set the  CAB title according to total checked items

                    // Calls  toggleSelection method from ListViewAdapter Class

                    // Count no.  of selected item and print it
                    mode.setTitle(checkedCount  + "  Selecionados");
                    return true;
                case R.id.reverter:
                    // Add  dialog for confirmation to delete selected item
                    // record.
                    AlertDialog.Builder  builder = new AlertDialog.Builder(
                            getContext());
                    builder.setMessage("Confirmar reciclagem do(s) disco(s) selecionado(s)?");

                    builder.setNegativeButton("Não", new  DialogInterface.OnClickListener() {

                        @Override
                        public void  onClick(DialogInterface dialog, int which) {
                            // TODO  Auto-generated method stub

                        }
                    });
                    builder.setPositiveButton("Sim", new  DialogInterface.OnClickListener() {

                        @Override
                        public void  onClick(DialogInterface dialog, int which) {
                            SparseBooleanArray selected = mDeletadosAdapter
                                    .getSelectedIds();
                            for (int i =  (selected.size() - 1); i >= 0; i--) {
                                if  (selected.valueAt(i)) {
                                    Record selecteditem = mDeletadosAdapter
                                            .getItem(selected.keyAt(i));
                                    // Remove  selected items following the ids
                                    mDeletadosAdapter.remove(selecteditem);
                                    recordsDeletadosGlobal.remove(selecteditem);
                                    ResultadosFragment.mAdapter.add(selecteditem);
                                    ResultadosFragment.recordsGlobal.add(selecteditem);

                                    Double priceSum = 0.0;
                                    for (int j = 0; j < ResultadosFragment.recordsGlobal.size(); j++){
                                        priceSum += ResultadosFragment.recordsGlobal.get(j).getmPrice();
                                        System.out.println("recordsGlobal.get(j).getmPrice(): " + ResultadosFragment.recordsGlobal.get(j).getmPrice());
                                    }
                                    System.out.println("priceSum: " + priceSum + "\nrecordsGlobal.size(): " + ResultadosFragment.recordsGlobal.size());
                                    Double mediaDouble = EstatisticasFragment.fazerMedia(priceSum, ResultadosFragment.recordsGlobal.size());
                                    String media = mediaDouble.toString();

                                    TextView mediaFinal = (TextView) EstatisticasFragment.rootView.findViewById(R.id.textViewMedia);
                                    mediaFinal.setVisibility(View.VISIBLE);
                                    media = QueryUtils.trimPrice(media);
                                    mediaFinal.setText("R$" + media);
                                    mediaFinal.setTextSize(50);
                                    Activity activity = (Activity) EstatisticasFragment.rootView.getContext();
                                    mediaFinal.setTextColor(ContextCompat.getColor(activity, R.color.colorPrice));

                                    int sumOfRecords = ResultadosFragment.recordsGlobal.size();

                                    Double desvioPadrao = EstatisticasFragment.calcularDesvioPadrao(mediaDouble, ResultadosFragment.recordsGlobal);
                                    Double coeficienteVariacao = EstatisticasFragment.calcularcoeficienteDeVariacaoDosRecords(mediaDouble, desvioPadrao);

                                    TextView totalDeRegistros = (TextView) EstatisticasFragment.rootView.findViewById(R.id.textViewTotalRegistros);
                                    String sumOfRecordsString = Integer.toString(sumOfRecords);
                                    totalDeRegistros.setText("Total de Registros: " + sumOfRecordsString +"\nDesvio Padrão: " + desvioPadrao + "\nC.V: " + coeficienteVariacao);
                                    totalDeRegistros.setTextSize(10);
                                    totalDeRegistros.setTextColor(ContextCompat.getColor(EstatisticasFragment.rootView.getContext(), R.color.colorPrice));
                                }
                            }
                            // Close CAB
                            mode.finish();
                            selected.clear();
                            mDeletadosAdapter.notifyDataSetChanged();
                            mDeletadosAdapter.notifyDataSetInvalidated();
                            ResultadosFragment.mAdapter.notifyDataSetChanged();
                            ResultadosFragment.mAdapter.notifyDataSetInvalidated();

                        }
                    });
                    AlertDialog alert =  builder.create();
                    alert.setTitle("Confirmation"); // dialog  Title
                    alert.show();
                    return true;
                default:
                    return false;
            }

        }

        @Override
        public void  onItemCheckedStateChanged(android.view.ActionMode mode,
                                               int position, long id, boolean checked) {
            // TODO  Auto-generated method stub
            final int checkedCount  = recordsDeletadosListView.getCheckedItemCount();
            // Set the  CAB title according to total checked items
            mode.setTitle(checkedCount  + "  Selecionado(s)");
            // Calls  toggleSelection method from ListViewAdapter Class
            mDeletadosAdapter.toggleSelection(position);
        }
    });



    recordsDeletadosListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            // Achar o record atual que foi clicado
            Record currentRecord = mDeletadosAdapter.getItem(position);

            // Converte o URL String em um objeto URI (para passar no construtor de Intent)
            Uri recordUri = Uri.parse(currentRecord.getmPermalink());

            Intent intent = new Intent(Intent.ACTION_VIEW, recordUri);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent);

        }
    });


    setHasOptionsMenu(true);

    return rootView;
}

----------------------------------------- EDITED-- ---------------------------------------

我所做的是创建一个设置为true的标志(intentAberto),告诉我意图已经开始。

recordListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                // Achar o record atual que foi clicado
                Record currentRecord = mAdapter.getItem(position);

                // Converte o URL String em um objeto URI (para passar no construtor de Intent)
                Uri recordUri = Uri.parse(currentRecord.getmPermalink());

                Intent intent = new Intent(Intent.ACTION_VIEW, recordUri);
                intentAberto = true;
                startActivity(intent);

            }

然后,在我的Loader类中,我在onStartLoading()方法中插入了一个条件。

@Override
protected void onStartLoading() {
    if (!ResultadosFragment.intentAberto)
        forceLoad();
}

当我按下后退按钮时,这阻止了forceLoad()启动。

就是这样!

感谢Prashanth Kondedath的回答。它让我思考并找到解决方案!

1 个答案:

答案 0 :(得分:0)

为什么不覆盖页面加载活动的backPress()事件,并为主活动添加额外的意图,您可以传递一些标记,如(Pageloaded = true)。并在你的主要活动中检查这个标志,如果它的真实不重新加载内容......这是最简单的做法.....