android片段重新加载(onCreate)每次按下后按钮

时间:2016-06-21 10:02:12

标签: android-fragments savestate onbackpressed recreate

我在我的项目中使用片段的android新手。我的片段第一次创建然后调用api并在片段中加载数据。在这里,当我点击任何项目我用另一个片段替换片段时,还有另一个api调用并将数据加载到片段。 现在这里为我生成了问题情况。 从这里我按回按钮。

片段重新加载与第一次创建相同,但它应该是在我转到下一个片段之前显示的数据。

所以请提供解决方案,我如何获得相同的数据,因为我离开意味着savedInstanceState数据。

我的第一个片段getCategory方法调用Api并获取数据第一次当我选择任何类别时我用另一个片段替换片段但是当我返回相同的getCategory方法时,调用执行与第一次相同的过程。

片段不应该再次调用api方法,它应该在此之前显示相同的类别。

我的第一个片段叫做api ......

public class LandingFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
     private String mParam1;
     private String mParam2;

     private GridLayoutManager gridLayoutManager;
     private static RecyclerView category_Grid;
     private Fragment myFragment = null;
     ProgressBar mProgressView;
     View mLoginFormView;
     private Category category;
     private CategoryAdapter categoryAdapter;
     private List<CategoryObject> rowListItem;
     private String productId;
     private OnFragmentInteractionListener mListener;

    public LandingFragment() {
       // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
      *
      * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment LandingFragment.
     */
     // TODO: Rename and change types and number of parameters
     public static LandingFragment newInstance(String param1, String param2)    {
        LandingFragment fragment = new LandingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
     }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v= inflater.inflate(R.layout.fragment_landing, container, false);
        return v;
    }

     @Override
     public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

         initViews(view);
         RecyclerViewListeners();
     }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
           mListener.onFragmentInteraction(uri);
        }
    }

    @Override
     public void onAttach(Activity context) {
        super.onAttach(context);

        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
     }

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

    /**
      * This interface must be implemented by activities that contain this
      * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     *     "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
     }

    private void initViews(final View v) {
        mLoginFormView = (View)v.findViewById(R.id.mainView);
        mProgressView = (ProgressBar)v.findViewById(R.id.login_progress);
        category_Grid = (RecyclerView)v.findViewById(R.id.cat_grid);
        category_Grid.setHasFixedSize(true);
        gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        category_Grid.setLayoutManager(gridLayoutManager);
     }

 private void RecyclerViewListeners(){
    category_Grid.addOnItemTouchListener(new    RecyclerTouchListener(getActivity(), category_Grid, new ItemClickListener(){
        @Override
        public void onClick(View view, int position) {

            String entityId = rowListItem.get(position).getCategoryId();
            String catName = rowListItem.get(position).getName();
            Integer ishave = rowListItem.get(position).getIshaveSubcategories();
            if(ishave==1) {
                myFragment = SubcategoryFragment.newInstance(""+catName, "" + entityId);
                ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
            }else{
                myFragment = ProductListFragment.newInstance("", "" + entityId);
                ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
            }
        }

        @Override
        public void onLongClick(View view, int position) {

        }
    }));
}

public void getCategory() {
    showProgress(true);
    String URL = getResources().getString(R.string.category_api);
    StringRequest req = new StringRequest(Request.Method.POST,URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            VolleyLog.v("Response:%n %s", response);
            Gson gson = new GsonBuilder().serializeNulls().create();
            try {
                JSONObject jsonObject = new JSONObject(response);
                if (jsonObject.getString("status").equals(getResources().getString(R.string.response_success))){
                    category = gson.fromJson(response, Category.class);
                    rowListItem = category.getCategory();
                    if(navigationUpdated){
                        someEventListener.someEvent(rowListItem);
                        navigationUpdated = false;
                    }
                    Log.d("CATEGORYID::::::::",""+rowListItem.get(1).getCategoryId());
                    categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
                    category_Grid.setAdapter(categoryAdapter);
                    categoryAdapter.notifyDataSetChanged();


                    return;
                }
                else if (jsonObject.getString("status").equals(getResources().getString(R.string.login_Er_respose))){
                    Log.e("","ERRORRRRRR");
                    return;
                }
            } catch (JSONException e) {
                showProgress(false);
                Log.e("My App", "Could not parse malformed JSON: \"" + response + "\"");
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
              showProgress(false);
              VolleyLog.e("Error: ", error.getMessage());
        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Content-Type","application/x-www-form-urlencoded");
            return params;
        }
    };
    AppController.getInstance().addToRequestQueue(req);
}

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime =   getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}

2 个答案:

答案 0 :(得分:3)

您可以检查rowListItem.size(),如果它的大小为0则调用getCategory()服务,否则从rowListItem加载数据。以下是我用于从arraylist加载数据的示例代码,如果它不为空:

if (mArrayArticle.size() == 0) {
    isDataLoading = true;
    mRecyclerList.setVisibility(View.INVISIBLE);
    getCategory();
} else {
    mHomeItemAdapter = new HomeItemAdapter(getActivity(), mArrayArticle, this);
    mRecyclerList.setAdapter(mHomeItemAdapter);
}

此处mArrayArticle是我的ArrayList,希望它能为您提供帮助。

答案 1 :(得分:1)

如需更多说明,我想告诉.. 我如何实现@Bhvk_AndroidBee解决方案

片段反向调用onActivityCreated方法首先override片段

中的此方法
  @Override
    public void onActivityCreated(Bundle savedInstanceState) {
       super.onActivityCreated(savedInstanceState);

      //here you can check null condition for rowListItem
    }
}

在onActivityCreated方法中我检查了那样的条件

    @Override
     public void onActivityCreated(Bundle savedInstanceState) {
       super.onActivityCreated(savedInstanceState);
        if(rowListItem!=null){

           categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
           category_Grid.setAdapter(categoryAdapter);
           categoryAdapter.notifyDataSetChanged();

       }else {

        //call the method for first time creating your view

           getCategory();

       }
    }

希望这对像我这样的更多挣扎者有所帮助......