Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CardView setCardBackgroundColor won't work

I have made an adapter of CardView through the RecyclerView for me to use the same template of card for this feature of mine.

The objective is to create certain cards with different colors, based on the parameter inc_status in INCCards.java. But it doesn't just seem to work.

Here's the source code for the template card:

item_inc_card.xml

<LinearLayout
    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="match_parent"
    android:paddingLeft="@dimen/spacing_medium"
    android:paddingRight="@dimen/spacing_medium"
    android:paddingTop="@dimen/spacing_medium"
    android:background="@color/tertiary">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="@dimen/spacing_none">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="@dimen/spacing_large"
                android:paddingRight="@dimen/spacing_large"
                android:paddingTop="@dimen/spacing_large"
                android:paddingBottom="@dimen/spacing_medium"
                android:id="@+id/relative_layout">

                <TextView
                    android:id="@+id/course_code"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentLeft="true"
                    android:textColor="@color/white"
                    android:textSize="@dimen/text_headline"
                    android:text="@string/course_code"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/course_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/course_code"
                    android:textColor="@color/white"
                    android:textSize="@dimen/text_subhead"
                    android:text="@string/course_title" />

                <TextView
                    android:id="@+id/faculty"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/white"
                    android:layout_below="@+id/course_title"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true"
                    android:textStyle="italic"
                    android:textSize="@dimen/text_body"
                    android:text="@string/faculty" />


                <ImageView
                    android:id="@+id/status_icon"
                    android:src="@drawable/icon_avatar"
                    android:layout_width="@dimen/size_user_icon"
                    android:layout_height="@dimen/size_user_icon"
                    android:layout_above="@+id/faculty"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentEnd="true" />

                <TextView
                    android:id="@+id/inc_grade"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="@dimen/text_body"
                    android:layout_below="@+id/status_icon"
                    android:layout_alignRight="@+id/status_icon"
                    android:layout_alignEnd="@+id/status_icon"
                    android:layout_alignLeft="@+id/status_icon"
                    android:layout_alignStart="@+id/status_icon"
                    android:gravity="center"
                    android:textAlignment="center"
                    android:textColor="@color/white"
                    android:text="@string/equiv_grade"/>

            </RelativeLayout>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="0.001dp"
                android:background="#FFFFFF"
                android:id="@+id/line_divider"/>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="@dimen/spacing_large"
                android:paddingRight="@dimen/spacing_medium"
                android:paddingBottom="@dimen/spacing_medium"
                android:layout_marginTop="@dimen/spacing_medium"
                android:id="@+id/semesterInfoLinearLayout">

                <TextView
                    android:id="@+id/section"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="@dimen/text_caption"
                    android:text="@string/section"
                    android:textColor="@color/white"
                    android:layout_weight="0.33" />

                <TextView
                    android:id="@+id/semester"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="@dimen/text_caption"
                    android:text="@string/semester"
                    android:textColor="@color/white"
                    android:layout_weight="0.33"
                    android:gravity="center" />

                <TextView
                    android:id="@+id/acad_year"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="@dimen/text_caption"
                    android:text="@string/acad_year"
                    android:textColor="@color/white"
                    android:layout_weight=".33"
                    android:gravity="right" />
            </LinearLayout>

        </LinearLayout>


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

</LinearLayout>

And for the fragment layout:

item_inc_card.xml

<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_inc_cards"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/tertiary"/>

To where each card is initialized by the object

INCCards.java

package ph.edu.amitypipduo.myiit;

public class INCCards {
    String course_code, course_title, faculty, section, semester, acad_year;
    int inc_status, status_icon;
    final String inc_grade = "INC 3.00";

    public INCCards(String course_code, String course_title, String faculty, String section, String semester, String acad_year, String inc_status) {
        this.course_code = course_code;
        this.course_title = course_title;
        this.faculty = faculty;
        this.section = section;
        this.semester = semester;
        this. acad_year = acad_year;

        switch (inc_status) {
            case "notice":
                this.inc_status = R.color.inc_notice;
                this.status_icon = R.drawable.inc_notice;
                break;
            case "alert":
                this.inc_status = R.color.inc_alert;
                this.status_icon = R.drawable.inc_alert;
                break;
            case "warning":
                this.inc_status = R.color.inc_warning;
                this.status_icon = R.drawable.inc_warning;
                break;
            case "danger":
                this.inc_status = R.color.inc_danger;
                this.status_icon = R.drawable.inc_danger;
                break;
        }

    }

}

I tried setting the background color of the card at method onBindViewHolder by:

cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);

as seen here in

INCAdapter.java

package ph.edu.amitypipduo.myiit;

import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class INCAdapter extends RecyclerView.Adapter<INCAdapter.CardViewHolder> {
    List<INCCards> inc_cards;

    public INCAdapter(List<INCCards> inc_cards){
        this.inc_cards = inc_cards;
    }

    @Override
    public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_inc_card, viewGroup, false);
        CardViewHolder card_view_holder = new CardViewHolder(view);
        return card_view_holder;
    }

    @Override
    public void onBindViewHolder(CardViewHolder cardViewHolder, int i) {
        cardViewHolder.course_code.setText(inc_cards.get(i).course_code);
        cardViewHolder.course_title.setText(inc_cards.get(i).course_title);
        cardViewHolder.faculty.setText(inc_cards.get(i).faculty);
        cardViewHolder.section.setText(inc_cards.get(i).section);
        cardViewHolder.semester.setText(inc_cards.get(i).semester);
        cardViewHolder.acad_year.setText(inc_cards.get(i).acad_year);
        cardViewHolder.inc_grade.setText(inc_cards.get(i).inc_grade);
        cardViewHolder.status_icon.setImageResource(inc_cards.get(i).status_icon);
        cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);
    }

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

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

    public static class CardViewHolder extends RecyclerView.ViewHolder {
        CardView card_view;
        TextView course_code, course_title, faculty, section, semester, acad_year, inc_grade;
        ImageView status_icon;


        CardViewHolder(View itemView) {
            super(itemView);
            card_view = (CardView) itemView.findViewById(R.id.card_view);

            course_code = (TextView) itemView.findViewById(R.id.course_code);
            course_title = (TextView) itemView.findViewById(R.id.course_title);
            faculty = (TextView) itemView.findViewById(R.id.faculty);
            inc_grade = (TextView) itemView.findViewById(R.id.inc_grade);
            section = (TextView) itemView.findViewById(R.id.section);
            semester = (TextView) itemView.findViewById(R.id.semester);
            acad_year = (TextView) itemView.findViewById(R.id.acad_year);

            status_icon = (ImageView) itemView.findViewById(R.id.status_icon);
        }
    }
}

Then initializing the data in the fragment class and inflating the layout:

INCMonitorFragment.java

package ph.edu.amitypipduo.myiit;

import android.app.Activity;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class INCMonitorFragment 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 OnFragmentInteractionListener mListener;

    private RecyclerView recycler_view;
    private LinearLayoutManager linear_layout_manager;
    private INCAdapter inc_adapter;

    private List<INCCards> inc_cards;

    private void initializeData() {
        inc_cards = new ArrayList<>();
        inc_cards.add(new INCCards("CSC 198", "Methods of Research", "Prof. Cyrus Gabilla", "CS-1A", "SECOND SEMESTER", "AY 2014-2015", "danger"));
        inc_cards.add(new INCCards("POLSCI 2", "Philippine Govt. & Const.", "Prof. Cyrus Gabilla", "AB4", "SUMMER SEMESTER", "AY 2013-2014", "warning"));
        inc_cards.add(new INCCards("ENG 2N", "Writing in Discipline", "Prof. Rabindranath Polito", "B4", "FIRST SEMESTER", "AY 2012-2013", "alert"));
        inc_cards.add(new INCCards("MATH 51", "I Forgot the Course Title", "Prof. Forgotten Name", "69", "SECOND SEMESTER", "AY 2012-2013", "notice"));
    }


    // TODO: Rename and change types and number of parameters
    public static INCMonitorFragment newInstance(String param1, String param2) {
        INCMonitorFragment fragment = new INCMonitorFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

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

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

        initializeData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_inc_monitor, container, false);
        recycler_view = (RecyclerView) view.findViewById(R.id.fragment_inc_cards);
        recycler_view.setHasFixedSize(true);

        linear_layout_manager = new LinearLayoutManager(getActivity().getApplicationContext());
        recycler_view.setLayoutManager(linear_layout_manager);

        inc_adapter = new INCAdapter(inc_cards);
        recycler_view.setAdapter(inc_adapter);

        return view;
    }

    // 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 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;
    }


}

But it only shows this:

enter image description here

Why does it not recognize the color? How come the R.drawable..... was recognized by the onBindViewHolder and not the R.color.....?

like image 713
anobilisgorse Avatar asked Jul 20 '15 08:07

anobilisgorse


People also ask

How to add elevation to CardView android?

To change CardView's elevation in a backward compatible way, use setCardElevation . CardView will use elevation API on Lollipop and before Lollipop, it will change the shadow size. To avoid moving the View while shadow size is changing, shadow size is clamped by getMaxCardElevation .

What is CardView in android?

CardView is a new widget in Android that can be used to display any sort of data by providing a rounded corner layout along with a specific elevation. CardView is the view that can display views on top of each other. The main usage of CardView is that it helps to give a rich feel and look to the UI design.

How do I customize my CardView?

Customized CardView First, add a CardView dependency to the application-level build. gradle file. Then create a drawable background for the cards. For that, create a new drawable resource file inside the drawable folder.


2 Answers

Change

cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);

to

int colorId = inc_cards.get(i).inc_status;
int color = cardViewHolder.card_view.getContext().getResources().getColor(colorId);
cardViewHolder.card_view.setCardBackgroundColor(color);

You are using the value from R.color instead of the value you set in your XML.

like image 200
Jared Rummler Avatar answered Sep 30 '22 12:09

Jared Rummler


I'm getting a more reliable color overriding with this line:

setBackgroundTintList(ColorStateList.valueOf(color));

instead of:

setCardBackgroundColor(color).
like image 31
brab84 Avatar answered Sep 30 '22 10:09

brab84