Nikita Mittal
Nikita Mittal

Reputation: 35

How to replace fragments on the onClick() of cardview?

I'm following material design. So can I replace a Fragment in the onClick() method of CardView with passing some data from RecyclerView.Adapter to the other Fragment?

Here's my code:

fragment_states.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/state"
    tools:context="nmittal.indiatour.States">

    <!--<include android:id="@+id/toolbar"-->
        <!--layout="@layout/toolbar"/>-->

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:divider="#ffffff"
        android:orientation= "vertical"
        android:dividerHeight="1px"
        android:layout_weight="1"
        android:gravity= "center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!--android:scrollbars="vertical"-->
</RelativeLayout>

States.java:

    public class States extends Fragment{

       private LinearLayoutManager linearLayoutManager;
        RecyclerView recyclerView;
        StateRecyclerViewAdapter stateRecyclerViewAdapter;
        List<StateName> stateNameList;
        String url1;
        JSONObject jsonObject;
        JSONArray cityArray;
        public static String Key;

        class GetFixture extends AsyncTask<Void, Void, Void>{

            private GetFixture(){

            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }   

            @Override
            protected Void doInBackground(Void... params) {

                String json = new AuthJSON().makeServiceCall(States.this.url1, 2);

                if (json!=null){
                    try {
                        States.this.jsonObject = new JSONObject(json);
                        Log.d("jsonObject", "new json Object");

                        States.this.cityArray = States.this.jsonObject.getJSONArray("Credentials");
                        Log.d("json Array", "User point array");
                        Log.d("Array Length", String.valueOf(States.this.cityArray.length()));
                        Log.d("len", "getarray length");

                        for (int i=0; i<States.this.cityArray.length(); i++){
                            States.Key = States.this.cityArray.getJSONObject(i).getString("AuthKey");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                else {
                    Log.e("JSON Data", "Didn't receive any data from server!");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
            }
        }
        public States() {
            // Required empty public constructor

        }

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

            recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
            recyclerView.setHasFixedSize(true);

            linearLayoutManager = new LinearLayoutManager(getActivity());
            recyclerView.setLayoutManager(linearLayoutManager);

            stateRecyclerViewAdapter = new StateRecyclerViewAdapter(getDataSet());

            recyclerView.setAdapter(stateRecyclerViewAdapter);              
            return view;
        }

        public List<StateName> getDataSet() {
            stateNameList = new ArrayList();
            stateNameList.add(new StateName("WestBengal"));
stateNameList.add(new StateName("Gujarat"));
stateNameList.add(new StateName("Delhi"));
stateNameList.add(new StateName("Kerala"));

            return stateNameList;
        }
    }

card_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:id="@+id/cardView"
        android:layout_marginLeft="-3dp"
        android:layout_marginRight="0dp"
        android:gravity="center_horizontal"
        android:focusable="true"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground"
        card_view:cardElevation="4dp"
        card_view:cardUseCompatPadding="true"
        card_view:cardCornerRadius="2dp">    

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:padding="8dp"
                android:textStyle="bold"
                android:textAlignment="center"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_gravity="center_horizontal"
                android:gravity="fill"
                android:text= ""
                android:textColor="#ffffff"
                android:layout_centerHorizontal= "true"
                android:id="@+id/text" />

        </android.support.v7.widget.CardView>

</RelativeLayout>

StateRecyclerViewAdapter.java:

public class StateRecyclerViewAdapter extends RecyclerView.Adapter<StateRecyclerViewAdapter.PlaceViewHolder>{

            static int i;
            private List<StateName> stateNameList;
            String string;

            public StateRecyclerViewAdapter(List<StateName> list){
                i=1;
                stateNameList = list;

            }

            public PlaceViewHolder onCreateViewHolder(ViewGroup viewGroup, int i){

                View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view, viewGroup, false);
                PlaceViewHolder placeViewHolder = new PlaceViewHolder(itemView);
                placeViewHolder.cardView.setOnClickListener(new StateRecyclerViewAdapter1(placeViewHolder, viewGroup));
                return placeViewHolder;
            }

            public void onBindViewHolder(PlaceViewHolder placeViewHolder, int i) {
                StateName stateName = stateNameList.get(i);
                placeViewHolder.stateName.setText(stateName.getName());
placeViewHolder.cardView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                //Here goes your desired onClick behaviour. Like:
                Toast.makeText(view.getContext(), "You have clicked " + view.getId(), Toast.LENGTH_SHORT).show(); //you can add data to the tag of your cardview in onBind... and retrieve it here with with.getTag().toString()..
               //You can change the fragment, something like this, not tested, please correct for your desired output:
                Activity activity = view.getContext();
                Fragment CityName = new CityName();
                //Create a bundle to pass data, add data, set the bundle to your fragment and:
                activity.getFragmentManager().beginTransaction().replace(R.id.fragment_container, cityName).addToBackStack(null).commit();     //Here m getting error                                  
            }
        });
            }

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

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

            @Override
            public int getItemViewType(int position) {
                return 0;
            }

            public static class PlaceViewHolder extends RecyclerView.ViewHolder {

                protected TextView stateName;
                protected CardView cardView;

                public PlaceViewHolder(View view) {
                    super(view);

                    stateName = (TextView) view.findViewById(R.id.text);
                    cardView = (CardView) view.findViewById(R.id.cardView);

                    switch (StateRecyclerViewAdapter.i) {
                        case CompletionEvent.STATUS_FAILURE:
                            cardView.setCardBackgroundColor(Color.parseColor("#DDEC407A"));
                            i++;
                        case CompletionEvent.STATUS_CONFLICT:
                            cardView.setCardBackgroundColor(Color.parseColor("#DD7986CB"));
                            i++;
                        case CompletionEvent.STATUS_CANCELED:
                            cardView.setCardBackgroundColor(Color.parseColor("#DD5E35B1"));
                            i++;
                        default:
                            cardView.setCardBackgroundColor(Color.parseColor("#DDFF6F00"));
                            StateRecyclerViewAdapter.i = 1;
                    }

                }
            }
        }

AndroidManifest.xml:

<activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:configChanges="keyboardHidden|orientation"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>

What should I do to replace Fragments. I had commented in the stateRecyclerview class where it should get replacd. Thx in advance!!

Upvotes: 2

Views: 9250

Answers (3)

kidustiliksew
kidustiliksew

Reputation: 463

Do this..

public static class PlaceViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

            protected TextView stateName;
            protected CardView cardView;

            public PlaceViewHolder(View view) {
                super(view);
                view.setOnClickListener(this);
                stateName = (TextView) view.findViewById(R.id.text);
                cardView = (CardView) view.findViewById(R.id.cardView);

                switch (StateRecyclerViewAdapter.i) {
                    case CompletionEvent.STATUS_FAILURE:
                        cardView.setCardBackgroundColor(Color.parseColor("#DDEC407A"));
                        i++;
                    case CompletionEvent.STATUS_CONFLICT:
                        cardView.setCardBackgroundColor(Color.parseColor("#DD7986CB"));
                        i++;
                    case CompletionEvent.STATUS_CANCELED:
                        cardView.setCardBackgroundColor(Color.parseColor("#DD5E35B1"));
                        i++;
                    default:
                        cardView.setCardBackgroundColor(Color.parseColor("#DDFF6F00"));
                        StateRecyclerViewAdapter.i = 1;
                }

                @Override
                public void onClick(View v) {
                        FragmentManager fm = getFragmentManager();

                        OtherFragment otherFragment = OtherFragment.newInstance(cityName);

                        fm.beginTransaction().replace(R.id.fragment_container, otherFragment).commit();
                }

        }
}

And your other fragment would look something like this..

public class OtherFragment extends Fragment {

    private static final String ARG_CITY_NAME = "city_name";

    public static OtherFragment newInstance(String cityName) {

        Bundle args = new Bundle();
        args.putSerializable(ARG_CITY_NAME, cityName);

        OtherFragment fragment = new OtherFragment();
        fragment.setArguments(args);
        return fragment;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        String cityName = (String) getArguments().getSerializable(ARG_CITY_NAME);

    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_layout, container, false);

        return view;
    }
}

Upvotes: 0

yennsarah
yennsarah

Reputation: 5517

public class StateRecyclerViewAdapter extends RecyclerView.Adapter<StateRecyclerViewAdapter.PlaceViewHolder>{

    static int i;
    private List<StateName> stateNameList;
    String string;

    //You don't need another class for the onClick behaviour:

    public StateRecyclerViewAdapter(List<StateName> list){
        i=1;
        stateNameList = list;
    }

    public PlaceViewHolder onCreateViewHolder(ViewGroup viewGroup, int i){

        View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view, viewGroup, false);
        return new PlaceViewHolder(itemView);
    }

    public void onBindViewHolder(PlaceViewHolder placeViewHolder, int i) {
        StateName stateName = stateNameList.get(i);
        placeViewHolder.stateName.setText(stateName.getName());
        placeViewHolder.cardView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                //Here goes your desired onClick behaviour. Like:
                Toast.makeText(view.getContext(), "You have clicked " + view.getId(), Toast.LENGTH_SHORT).show(); //you can add data to the tag of your cardview in onBind... and retrieve it here with with.getTag().toString()..
               //You can change the fragment, something like this, not tested, please correct for your desired output:
                AppCompatActivity activity = (AppCompatActivity) view.getContext();
                MyFragment myFragment = new MyFragment();
                //Create a bundle to pass data, add data, set the bundle to your fragment and:
                activity.getSupportFragmentManager().beginTransaction().replace(R.id.yourContainerId, myFragment).addToBackStack(null).commit();                                       
            }
        });
    }

    @Override
    public long getItemId(int position) {
        return 0;       //you should not return 0 for every item, change it to position or your a possible id, if you have one.
    }

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

    @Override
    public int getItemViewType(int position) {
        return 0;
    }

Upvotes: 11

Hiren Patel
Hiren Patel

Reputation: 52810

Can you please try this one ?

 public static class PlaceViewHolder extends RecyclerView.ViewHolder {

  protected TextView stateName;
  protected CardView cardView;

  public PlaceViewHolder(View view) {
         super(view);

   stateName = (TextView) view.findViewById(R.id.text);
   cardView = (CardView) view.findViewById(R.id.cardView);

   cardView.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
         // Perform click listener of CardView
    }
  });

 // Other tasks

  }
}

Hope this will help you.

Upvotes: 0

Related Questions