单击Cardview项时更改颜色?

时间:2019-02-21 11:30:13

标签: android

卡的背景颜色为黑木炭。我已经写了一个代码,但是没有用。请帮帮我。

    GridLayout mainGrid;
    mainGrid=(GridLayout)findViewById(R.id.mainGrid);
    setToggleEvent(mainGrid);
    private void setToggleEvent(GridLayout mainGrid) {

    for (int i=0;i<mainGrid.getChildCount();i++)
    {
        final CardView cardView=(CardView)mainGrid.getChildAt(i);

        cardView.setCardBackgroundColor(Color.parseColor("#36454F"));

        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(cardView.getCardBackgroundColor().getDefaultColor()==-1)
                {
                    cardView.setCardBackgroundColor(Color.parseColor("#CC9933"));
                    Toast.makeText(Dashboardnew.this, "true", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    cardView.setCardBackgroundColor(Color.parseColor("#51d8c7"));
                    Toast.makeText(Dashboardnew.this, "false", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

尝试类似

if(cardView.getCardBackgroundColor().getDefaultColor()!=Color.parseColor("#51d8c7"))
            {
                cardView.setCardBackgroundColor(Color.parseColor("#51d8c7"));
                Toast.makeText(Dashboardnew.this, "false", Toast.LENGTH_SHORT).show();
            }
            else
            {
                cardView.setCardBackgroundColor(Color.parseColor("#CC9933"));
                Toast.makeText(Dashboardnew.this, "true", Toast.LENGTH_SHORT).show();

            }