维护RecyclerView和片段后退按钮

时间:2016-06-20 21:53:00

标签: android android-fragments android-recyclerview

我目前无法在点击我的recyclerview适配器的详细活动后将我的片段恢复到之前的状态。详细活动中的后退按钮将我返回到没有数据的空片段。

这是详细活动类

**
 * Provides UI for the Detail page with Collapsing Toolbar.
 */
public class DetailActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String EXTRA_POSITION = "position";
    private Boolean isFabOpen = false;
    private FloatingActionButton fab,fab1,fab2;
    private Animation fab_open,fab_close,rotate_forward,rotate_backward;
    private CollapsingToolbarLayout collapTool;
    private LinearLayout linLayout;
    private boolean isFavorited;
    private boolean isIgnored;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        fab = (FloatingActionButton)findViewById(R.id.fab);
        fab1 = (FloatingActionButton)findViewById(R.id.fab1);
        fab2 = (FloatingActionButton)findViewById(R.id.fab2);
        fab_open = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open);
        fab_close = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fab_close);
        rotate_forward = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_forward);
        rotate_backward = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_backward);
        fab.setOnClickListener(this);
        fab1.setOnClickListener(this);
        fab2.setOnClickListener(this);

        //Getting the details passed from the last activity to parse proper detail display
        Intent intent = getIntent();
        Bundle bd = intent.getExtras();
        String titleText = (String) bd.get("titleText");
        String descriptionText = (String) bd.get("description");
        String locations = (String) bd.get("locations");
        String assetTypes = (String) bd.get("assetTypes");
        String propertyStatuses = (String) bd.get("propertyStatuses");
        String buyerId = (String) bd.get("buyer_id") + "";

        //Buyer ID testing if proper ID is passed through
        //Toast.makeText(getApplicationContext(),buyerId,Toast.LENGTH_SHORT).show();
        isFavorited = (Boolean) bd.get("favorited");
        isIgnored = (Boolean) bd.get("ignored");

        //If item was favorited from previous page, adjust accordingly
        if(isFavorited) {
            fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
            fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
            fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
            isFavorited = true;
            isIgnored = false;
        }
        //If item was ignored from previous page, adjust accordingly
        if(isIgnored) {
            fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
            fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
            fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
            isIgnored = true;
            isFavorited = false;
        }
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        linLayout = (LinearLayout) findViewById(R.id.linLay);
        collapTool = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        linLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isFabOpen) {
                    fab.startAnimation(rotate_backward);
                    fab1.startAnimation(fab_close);
                    fab2.startAnimation(fab_close);
                    fab1.setClickable(false);
                    fab2.setClickable(false);
                    isFabOpen = false;
                }
            }
        });

        collapTool.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isFabOpen) {
                    fab.startAnimation(rotate_backward);
                    fab1.startAnimation(fab_close);
                    fab2.startAnimation(fab_close);
                    fab1.setClickable(false);
                    fab2.setClickable(false);
                    isFabOpen = false;
                }
            }
        });

        locations = locations.replace("Locations | ", "");
        assetTypes = assetTypes.replace("Asset Types | ", "");
        propertyStatuses = propertyStatuses.replace("Property Statuses | ", "");

        // Set Collapsing Toolbar layout to the screen
        CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        // Set title of Detail page
        // collapsingToolbar.setTitle(getString(R.string.item_title));

        assert fab2 != null;
        fab2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isFavorited) {
                    fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
                    fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
                    fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
                    //Snackbar.make(v, "Favorited...",Snackbar.LENGTH_LONG).show();
                    isFavorited = true;
                    isIgnored = false;
                } else {
                    fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
                    fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
                    /*Snackbar.make(v, "Unfavorited...",
                            Snackbar.LENGTH_LONG).show();
                            */
                    isFavorited = false;
                }
            }
        });

        assert fab1 != null;
        fab1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isIgnored) {
                    fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
                    fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
                    fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
                    isIgnored = true;
                    isFavorited = false;
                } else {
                    fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
                    fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
                    /*Snackbar.make(v, "Unfavorited...",
                            Snackbar.LENGTH_LONG).show();
                            */
                    isIgnored = false;
                }
            }
        });



        int postion = getIntent().getIntExtra(EXTRA_POSITION, 0);
        Resources resources = getResources();
        String[] places = resources.getStringArray(R.array.city_array);
        collapsingToolbar.setTitle(titleText);

        String[] placeDetails = resources.getStringArray(R.array.city_array);
        TextView placeDetail = (TextView) findViewById(R.id.place_detail);
        placeDetail.setText(descriptionText);

        String[] placeLocations = resources.getStringArray(R.array.city_array);
        TextView placeLocation =  (TextView) findViewById(R.id.place_location);
        placeLocation.setText(locations);

        TextView assetDetails = (TextView) findViewById(R.id.asset_details);
        assetDetails.setText(assetTypes);

        TextView propertyDetails = (TextView) findViewById(R.id.status_details);
        propertyDetails.setText(propertyStatuses);

        /*
        TextView investmentDetails = (TextView) findViewById(R.id.investment_details);
        investmentDetails.setText(investmentRangeMin);
        */

        /*

        TypedArray placePictures = resources.obtainTypedArray(R.array.city_array);
        ImageView placePicutre = (ImageView) findViewById(R.id.image);
        placePicutre.setImageDrawable(placePictures.getDrawable(postion % placePictures.length()));

        placePictures.recycle();
        */
    }

这是我的recyclerView适配器,它有一个用于项目视图的onclicklistener,用于创建详细活动。

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {

    private Activity activity;
    private LayoutInflater inflater;
    private static List<BuyerProfile> profileItems;
    private static boolean itemFavorited;

    RVAdapter(List<BuyerProfile> profiles) {
        this.profileItems = profiles;
    }

    public static class PersonViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        TextView description;
        TextView locations;
        TextView id;
        TextView investmentRange;
        TextView investmentRangeMax;
        TextView assetTypes;
        TextView propertyStatuses;
        TextView profileId;
        ImageView headerImage;
        Button favoriteButton;
        Button ignoreButton;
        CardView cardView;
        private ImageView spacer;
        private boolean favorited = false;
        private boolean ignored = false;
        PersonViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.titleText);
            description = (TextView) itemView.findViewById(R.id.descriptionText);
            investmentRange = (TextView) itemView.findViewById(R.id.investment);
            //investmentRangeMax = (TextView) itemView.findViewById(R.id.investmentRangeMax);
            locations = (TextView) itemView.findViewById(R.id.locations);
            id = (TextView) itemView.findViewById(R.id.profileNumber);
            headerImage = (ImageView) itemView.findViewById(R.id.imgBillionaire);
            assetTypes = (TextView) itemView.findViewById(R.id.assetTypes);
            propertyStatuses = (TextView) itemView.findViewById(R.id.propertyStatuses);
            favoriteButton = (Button) itemView.findViewById(R.id.action_button);
            ignoreButton = (Button) itemView.findViewById(R.id.ignore_button);
            cardView = (CardView) itemView.findViewById(R.id.cv);
            profileId = (TextView) itemView.findViewById(R.id.buyer_id);
            spacer = (ImageView) itemView.findViewById(R.id.spacerImage);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int i = getAdapterPosition();
                    Context context = v.getContext();
                    Intent intent = new Intent(context, DetailActivity.class);
                    intent.putExtra(DetailActivity.EXTRA_POSITION, getAdapterPosition());
                    intent.putExtra("titleText", name.getText());
                    intent.putExtra("description", description.getText());
                    intent.putExtra("locations", locations.getText());
                    intent.putExtra("assetTypes", assetTypes.getText());
                    intent.putExtra("propertyStatuses", propertyStatuses.getText());
                    intent.putExtra("favorited", favorited);
                    intent.putExtra("ignored", ignored);
                    HomeFragment homeReturn = new HomeFragment();
                    // intent.putExtra("buyer_id", profileId.getText());
                    //intent.putExtra("investmentRangeMin", investmentRangeMin.getText());
                    context.startActivity(intent);
                }
            });

            /*
            favoriteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!favorited) {
                        spacer.setVisibility(View.VISIBLE);
                        headerImage.setBackgroundColor(Color.parseColor("#7E57C2"));
                        favorited = true;
                        ignored = false;
                    } else {
                        spacer.setVisibility(View.INVISIBLE);
                        favorited = false;
                        headerImage.setBackgroundColor(Color.parseColor("#42A5F5"));
                    }
                }
            });
            */

            ignoreButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!ignored) {
                        spacer.setVisibility(View.VISIBLE);
                        headerImage.setBackgroundColor(Color.parseColor("#EF5350"));
                        favorited = false;
                        ignored = true;
                    } else {
                        ignored = false;
                        spacer.setVisibility(View.INVISIBLE);
                        headerImage.setBackgroundColor(Color.parseColor("#133253"));
                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return profileItems.size();
    }

    @Override
    public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
        PersonViewHolder pvh = new PersonViewHolder(v);
        return pvh;
    }

    @Override
    public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
        final PersonViewHolder selectedCard = personViewHolder;
        selectedCard.name.setText(profileItems.get(i).getBuyerProfTitle());
        selectedCard.description.setText(profileItems.get(i).getDescription());
        selectedCard.locations.setText("Locations |  " + profileItems.get(i).parseLocations());
        selectedCard.assetTypes.setText("Asset Types | " + profileItems.get(i).getAssetTypes());
        selectedCard.propertyStatuses.setText("Property Statuses | " + profileItems.get(i).getPropertyStatuses());
        selectedCard.investmentRange.setText("Investment Range | $125,000 - $250,000");
        final int position = i;
        personViewHolder.ignoreButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                profileItems.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, getItemCount());
            }
        });

        selectedCard.favoriteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!selectedCard.favorited) {
                    profileItems.get(position).favoriteItem();
                    selectedCard.spacer.setVisibility(View.VISIBLE);
                    selectedCard.spacer.setBackgroundColor(Color.parseColor("#FFF176"));
                    selectedCard.headerImage.setBackgroundColor(Color.parseColor("#7E57C2"));
                    selectedCard.favorited = true;
                    selectedCard.ignored = false;
                } else {
                    profileItems.get(position).unfavoriteItem();
                    selectedCard.favorited = false;
                    selectedCard.headerImage.setBackgroundColor(Color.parseColor("#133253"));
                }
            }
        });
        //personViewHolder.profileId.setText(profileItems.get(i).getProfileId() + "");
        //personViewHolder.investmentRangeMin.setText(profileItems.get(i).getInvestmentRangeMin());
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
}

最后这是我的主要片段,它包含了recyclerview。

public class HomeFragment extends Fragment {
    private CustomListAdapter listAdapter;
    //private static final String profileUrl = "http://172.16.98.152:3000/apip/buyers/profiles";
    private static final String matchesUrl = "http://172.16.98.152:3000/apip/sellers/profiles/1/matches";
    private String matched = "http://172.16.98.152:3000/apip/sellers/profiles/";
    private ProgressDialog pDialog;
    private ListView listView;
    private List<BuyerProfile> buyersProfiles = new ArrayList<BuyerProfile>();
    private View root;
    private TextView noItems;
    private TextView search;
    private TextView searchSecondLine;
    private LinearLayoutManager llm;
    private String profileUrlString;
    private String KEY_RECYCLER_STATE = "recycleSave";
    private Bundle viewState;
    private Bundle arguments;
    private RecyclerView rv;
    private int mStackLevel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_home, container, false);
        noItems = (TextView) root.findViewById(R.id.empty_view);
        search = (TextView) root.findViewById(R.id.search);
        searchSecondLine = (TextView) root.findViewById(R.id.matchesSecondLine);
        rv = (RecyclerView) root.findViewById(R.id.rv);
        rv.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        llm = new LinearLayoutManager(getActivity());
        rv.setLayoutManager(llm);
        rv.setItemAnimator(new DefaultItemAnimator());
        final RVAdapter recyclerAdapter = new RVAdapter(buyersProfiles);
        rv.setAdapter(recyclerAdapter);
        rv.setHasFixedSize(true);
        RequestQueue mRequestQueue;
        arguments = getArguments();

        if(savedInstanceState != null) {
            matched = matched + savedInstanceState.getString("profileArgs") + "/matches";
        } else {
            if(arguments != null && arguments.containsKey("profileId")) {
                matched = matched + arguments.getString("profileId") + "/matches";
                search.setText("Search: " + arguments.getString("locations") + " " + arguments.getString("assetTypes"));
                searchSecondLine.setVisibility(View.VISIBLE);
                searchSecondLine.setText(arguments.getString("propertyStatuses"));
            } else {
                matched = "http://172.16.98.152:3000/apip/sellers/profiles/1/matches";
                noItems.setVisibility(View.VISIBLE);
                searchSecondLine.setVisibility(View.INVISIBLE);
                rv.setVisibility(View.INVISIBLE);
                search.setVisibility(View.INVISIBLE);
            }
        }
        Cache cache = new DiskBasedCache(getActivity().getCacheDir(), 1024 * 1024);

        Network network = new BasicNetwork(new HurlStack());
        mRequestQueue = new RequestQueue(cache, network);
        mRequestQueue.start();


        JsonArrayRequest profileRequest = new JsonArrayRequest(matched,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject obj = response.getJSONObject(i);
                                BuyerProfile parsedProfile = new BuyerProfile();
                                parsedProfile.setBuyerProfTitle(obj.getString("title"));
                                parsedProfile.setDescription(obj.getString("description"));
                                parsedProfile.setLocations(obj.getString("location"));
                                parsedProfile.setAssetTypes(obj.getString("asset_type"));
                                //parsedProfile.setProfileId(obj.getString("id"));
                                parsedProfile.setPropertyStatuses(obj.getString("property_status"));
                                //parsedProfile.setProfileId(obj.getInt("buyer_profile_id"));
                                parsedProfile.unfavoriteItem();
                                buyersProfiles.add(parsedProfile);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        recyclerAdapter.notifyDataSetChanged();
                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        //hidePDialog();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Toast.makeText(selectBuyerProfile.this,"Error",Toast.LENGTH_LONG).show();

            }
        });
        mRequestQueue.add(profileRequest);
        /*
        if(buyersProfiles.isEmpty()) {
            rv.setVisibility(View.GONE);
            noItems.setVisibility(View.VISIBLE);
        }
        */
        return root;
    }

    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(arguments != null && arguments.containsKey("profileId")) {
            outState.putString("profileArgs", arguments.getString("profileId"));
        }
    }
}

我不确定我需要恢复哪些类以及如何在从详细活动中单击返回后恢复HomeFragment中的先前细节和图像。我能够在我的清单中描述一个父活动,但是主要类包含一切是片段而且android不允许你选择父片段!任何想法或帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

尝试从声明中删除List的初始化。

  

private List buyerProfiles = new ArrayList();

如果List为null,则在onCreateView方法中进行初始化。