已在片段

时间:2015-10-06 04:38:18

标签: android listview android-fragments

在我的应用程序中有一个片段类(TabFragmentComerTiposRestaurante)。它还有两个标签片段(案例0:PrimaryFragmentComerTiposRestaurante,案例1:SocialFragmentComerTiposRestaurante)。 在两个片段类上都有一个列表视图。单击此列表中的项目时,将显示另一个片段类(PrimaryFragmentComer。

简化这个架构:

TabFragmentComerTiposRestaurante(#F1)
-[PrimaryFragmenComerTiposRestaurante](#F11)--[PrimaryFragmentComer](#F111)
-[SocialFragmentComerTiposRestaurante](#F12)--[SocialFragmentComer](#F121)

我需要解决的问题如下:

如果在(#F111)或(#F121)用户点击后退按钮,则再次加载来自#F11和#F12的列表视图项目。这意味着,如果在第一个#F11呼叫中有一个名为" Cocina americana"的项目,然后从#F111返回到#F11或从#F121返回到#F12,那么现在有两个相同的项目:第一排= Cocina americana,第二排= Cocina americana。每次用户从#F11或#F12转到#F111或#F112时都会发生这种情况。

您可以在此找到

的代码

F1:

public class TabFragmentComerTiposRestaurante extends Fragment {

    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 2 ;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /**
         *Inflate tab_layout and setup Views.
         */
            View x =  inflater.inflate(R.layout.tab_layout_tipo_rte,null);
            tabLayout = (TabLayout) x.findViewById(R.id.tabs);
            viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                    tabLayout.setupWithViewPager(viewPager);
                   }
        });

        return x;

    }

    class MyAdapter extends FragmentPagerAdapter{

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

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position)
        {
          switch (position){
              case 0 : return new PrimaryFragmentComerTiposRestaurante();
              case 1 : return new SocialFragmentComerTiposRestaurante();


          }
        return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "CIUDAD JUAREZ";
                case 1 :
                    return "EL PASO";



            }
                return null;
        }
    }

}

#F11的代码

public class PrimaryFragmentComerTiposRestaurante extends Fragment implements AdapterView.OnItemClickListener {

    private OnFragmentInteractionListener mListener;

    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Movies json url
    private static final String url = "..hiddene here";
    private ProgressDialog pDialog;
    private List<TipoRestaurante> tipoRestauranteList = new ArrayList<TipoRestaurante>();
    private ListView listView;
    private CustomListAdapterTipoRte adapter;





    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.primary_layout_tiporte, null);
    }

    @Override
    public void onActivityCreated(Bundle state) {
        super.onActivityCreated(state);



        listView = (ListView) getView().findViewById(R.id.list);
        adapter = new CustomListAdapterTipoRte (getActivity(), tipoRestauranteList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(this);

        pDialog = new ProgressDialog(getActivity());
        // Showing progress dialog before making http request
        pDialog.setMessage("Procesando tipos..");
        pDialog.show();


        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();
    Log.d("estoy aqui","estoy");
                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                TipoRestaurante restaurante = new TipoRestaurante();
                                restaurante.setId_tipo(obj.getInt("id_tipo"));
                                restaurante.setNombre_tipo(obj.getString("nombre_tipo"));

                                restaurante.setFoto_tipo(obj.getString("foto_tipo"));

                                Log.d(TAG, response.toString());

                                // adding movie to movies array
                                tipoRestauranteList.add(restaurante);
                                pDialog = new ProgressDialog(getActivity());
                                pDialog.setMessage(obj.optString("id_tipo"));
                               // pDialog.show();

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }


    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        TipoRestaurante rteActual = (TipoRestaurante) adapter.getItem(position);
        String msg = "Has elegido el tipo " + rteActual.getNombre_tipo();
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();

               Fragment newFragment = new PrimaryFragmentComer();


        Bundle args = new Bundle();
        args.putInt("myIntLabel", 2);
        args.putString("myStringLabel", rteActual.getNombre_tipo());
//and you can add all you want to that bundle like this
        newFragment.setArguments(args);


        if (mListener != null) {
            mListener.onFragmentInteraction(newFragment);
        }

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Fragment fragment);
    }
}

现在代码#F111:

public class PrimaryFragmentComer extends Fragment implements AdapterView.OnItemClickListener {



    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Movies json url
    private static final String url = "...hidden here";
    private ProgressDialog pDialog;
    private List<Restaurante> restauranteList = new ArrayList<Restaurante>();
    private ListView listView;
    private CustomListAdapterRte adapter;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.primary_layout_comer, null);

    }

    @Override
    public void onActivityCreated(Bundle state) {
        super.onActivityCreated(state);



        Bundle args = getArguments();
        String hola = args.getString("myStringLabel");

        Log.d("TIPO RTE", hola);

        listView = (ListView) getView().findViewById(R.id.list);
        adapter = new CustomListAdapterRte (getActivity(), restauranteList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(this);

        pDialog = new ProgressDialog(getActivity());
        // Showing progress dialog before making http request
        pDialog.setMessage("Procesando restaurantes...");
        pDialog.show();






        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url+hola,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Restaurante restaurante = new Restaurante();
                                restaurante.setId_rte(obj.getInt("id_rte"));
                                restaurante.setNombre(obj.getString("nombre_rte"));
                                restaurante.setDescripcion(obj.getString("descripcion_rte"));
                                restaurante.setLatitud(obj.getDouble("latitud_rte"));
                                restaurante.setLongitud(obj.getDouble("longitud_rte"));
                                restaurante.setDireccion(obj.getString("direccion_rte"));
                                restaurante.setWeb(obj.getString("web_rte"));
                                restaurante.setTel_rte(obj.getString("tel_rte"));
                                restaurante.setTel_reservas(obj.getString("tel_reservas"));
                                restaurante.setFoto(obj.getString("foto_rte"));
                                restaurante.setCalificacion(obj.getDouble("calificacion_rte"));
                                restaurante.setTipo_rte(obj.getString("tipo_rte"));
                                restaurante.setFacebook(obj.getString("facebook_rte"));
                                restaurante.setTwitter(obj.getString("google_rte"));
                                restaurante.setZona(obj.getString("zona_rte"));
                                restaurante.setCiudad(obj.getInt("ciudad"));
                                restaurante.setPoi(obj.getInt("poi"));



                                // adding movie to movies array
                                restauranteList.add(restaurante);
                                pDialog = new ProgressDialog(getActivity());
                                pDialog.setMessage(obj.optString("id_rte"));
                               // pDialog.show();

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }


    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Restaurante rteActual = (Restaurante) adapter.getItem(position);
        String msg = "Elegiste el restaurante " + rteActual.getNombre();
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();

        Intent intent = new Intent(getActivity(), Detalle_Restaurante.class);

        intent.putExtra("id_rte", rteActual.getId_rte());
        intent.putExtra("nombre_rte", rteActual.getNombre());
        intent.putExtra("descripcion_rte", rteActual.getDescripcion());
        intent.putExtra("latitud_rte", rteActual.getLatitud());
        intent.putExtra("longitud_rte", rteActual.getLongitud());
        intent.putExtra("direccion_rte", rteActual.getDireccion());
        intent.putExtra("web_rte", rteActual.getWeb());
        intent.putExtra("tel_rte", rteActual.getTel_rte());
        intent.putExtra("tel_reservas", rteActual.getTel_reservas());
        intent.putExtra("foto_rte", rteActual.getFoto());
        intent.putExtra("calificacion_rte", rteActual.getCalificacion());
        intent.putExtra("tipo_rte", rteActual.getTipo_rte());
        intent.putExtra("facebook_rte", rteActual.getFacebook());
        intent.putExtra("google_rte", rteActual.getTwitter());
        intent.putExtra("zona_rte", rteActual.getZona());
        intent.putExtra("ciudad_rte", rteActual.getCiudad());
        intent.putExtra("poi_rte", rteActual.getPoi());


        startActivity(intent);




    }


}

1 个答案:

答案 0 :(得分:1)

如评论中所述,

正在describe SchoolService do Given(:school) { create(:school_with_applications) } Given(:service) { School.new(@school) } describe 'create_default_programs_and_year_grades!' do context 'checks program size' do When { service.create_default_programs_and_year_grades! } Then { expect(school.programs.size).to eq 3 } end end end 方法中将数据读入tipoRestauranteList,以避免在onResponse()之后写tipoRestauranteList.clear()

您的hidePDialog()也会发生同样的情况。这样做可以纠正同样的问题。 :)