3

For a personal project, i'm building an app which shows the current tables of the most popular football (or should i say soccer?) leagues in Europe. The table is a recyclerview, and each team inside it is a cardview. At the begining when my device is on portrait mode, everything shows up fine, but the problem starts when i change to landscape mode and then back to portrait. After that, i see another layer of my cardviews, beneath my current cardviews, and everything gets really ugly.

This is how it looks when everything gets messy

My recyclerview adapter:

public class TeamAdapter extends RecyclerView.Adapter<TeamAdapter.TeamViewHolder> {

private TeamLeagueStandings[] teams;
public TeamAdapter(TeamLeagueStandings[] teams){
    this.teams=teams;
}

@Override
public TeamAdapter.TeamViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.
            from(parent.getContext()).
            inflate(R.layout.card_view_team, parent, false);

    return new TeamViewHolder(itemView);
}

@Override
public void onBindViewHolder(TeamAdapter.TeamViewHolder holder, int position) {
    TeamLeagueStandings team = teams[position];
    holder.teamname.setText(team.getTeamName());
    holder.matches.setText(Integer.toString(team.getCurGames()));
    holder.wins.setText(Integer.toString(team.getWins()));
    holder.draws.setText(Integer.toString(team.getDraws()));
    holder.losses.setText(Integer.toString(team.getLosses()));
    holder.gd.setText(Integer.toString(team.getGoalDifference()));
    holder.points.setText(Integer.toString(team.getPoints()));

}

@Override
public int getItemCount() {
    return teams.length;
}}

My view holder (inner class inside the adapter):

public static class TeamViewHolder extends RecyclerView.ViewHolder{

        protected TextView teamname;
        protected TextView matches;
        protected TextView wins;
        protected TextView draws;
        protected TextView losses;
        protected TextView gd;
        protected TextView points;

        public TeamViewHolder(View itemView) {

            super(itemView);
            teamname=itemView.findViewById(R.id.teamName_txtview);
            matches=itemView.findViewById(R.id.matches_txtview);
            wins=itemView.findViewById(R.id.wins_txtview);
            draws=itemView.findViewById(R.id.draws_txtview);
            losses=itemView.findViewById(R.id.losses_txtview);
            gd=itemView.findViewById(R.id.gd_txtview);
            points=itemView.findViewById(R.id.points_txtview);


        }

    }

Finally, my main fragment, where i declare the recyclerview:

public class TableStandingsFragment 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";

    TeamAdapter adapter;

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

    private OnFragmentInteractionListener mListener;

    public TableStandingsFragment() {
        // 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 BlankFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TableStandingsFragment newInstance(String param1, String param2) {
        TableStandingsFragment fragment = new TableStandingsFragment();
        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);
        }
    }

    public TeamLeagueStandings [] GetPLTeams() throws IOException, JSONException {
        URL urlPL= League_standings.GetPLQuery();
        TeamLeagueStandings[] teams=League_standings.LeagueStandingsArray(urlPL);
        return  teams;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        // Inflate the layout for this fragment
        View v= inflater.inflate(R.layout.fragment_table, container, false);

        try {
            adapter= new TeamAdapter(GetPLTeams());
            RecyclerView recyclerView =  (RecyclerView) v.findViewById(R.id.recyler_teams);
            recyclerView.setHasFixedSize(true);
            recyclerView.setAdapter(adapter);
            recyclerView.addItemDecoration(new VerticalSpaceItemDecorator(30));
            LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(layoutManager);


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


        return v;
    }


    // 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(Context 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;
    }
    class VerticalSpaceItemDecorator extends RecyclerView.ItemDecoration {

        private final int spacer;

        public VerticalSpaceItemDecorator(int spacer) {
            this.spacer = spacer;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.bottom = spacer;
        }
    }
    /**
     * 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);
    }
}

Of course, there is more code that i didn't upload, i think that this code that i do upload is enough in order to solve this problem. Thanks!!

Shayts
  • 107
  • 9

2 Answers2

1

In your Activity try this code for fragment transaction

 getSupportFragmentManager().beginTransaction()
                    .replace(your container id, TableStandingsFragment.newInstance(param1,param2), TableStandingsFragment.class.getSimpleName())
                    .commitAllowingStateLoss();

Make sure you are importing right Fragment in TableStandingsFragment

import android.support.v4.app.Fragment;
Vinayak B
  • 4,430
  • 4
  • 28
  • 58
  • Thank you mate, It solved my problem! I think that my mistake was that i just added more and more fragments on each other, and that caused the mess. – Shayts Aug 14 '17 at 08:51
0

Remove recyclerView.setHasFixedSize(true);from you code and set your cardView height to wrap_content. You have to configure recyclerview before setting adapter.

Your recycler view initialization should be like this.

RecyclerView recyclerView =  (RecyclerView) v.findViewById(R.id.recyler_teams);
            recyclerView.addItemDecoration(new VerticalSpaceItemDecorator(30));
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            recyclerView.setAdapter(adapter);

If you want to know more about hasFixedSize(true) look at here. https://stackoverflow.com/a/40707099/5558150

https://stackoverflow.com/a/33365341/5558150

Bhuvanesh BS
  • 13,474
  • 12
  • 40
  • 66