[英]Android - CardView background always grey
我正在嘗試以編程方式更改CardView顏色。
這是我的CardView:
<android.support.v7.widget.CardView
android:id="@+id/createsub_card"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp">
這就是我設置背景顏色的方式:
CardView card = (CardView) findViewById(R.id.createsub_card);
card.setCardBackgroundColor(sub.getColor());
在這種情況下, sub.getColor()
返回此顏色:
<color name="color_black">#000000</color>
應該是黑色的。 仍然我的CardView看起來像這樣:
關於為什么會發生以及如何解決的任何想法?
我假設問題來自sub.getColor() 。 首先, 正確返回顏色代碼。
你可以嘗試一下
cardView.setCardBackgroundColor(Color.parseColor("#000000"));
要么
cardView.setCardBackgroundColor(getResources().getColor(R.color.color_black));
問題是sub.getColor(),您返回顏色id(R.color.color_black)而不是顏色代碼。 請參閱下面的代碼
sample.xml中
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="@+id/createsub_card"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_margin="10dp">
</android.support.v7.widget.CardView>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Click"
android:layout_below="@+id/createsub_card"
android:layout_centerHorizontal="true"
android:layout_marginTop="13dp" />
</RelativeLayout>
SampleActivity.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.Button;
/**
* Created by Magesh on 5/4/2017.
*/
public class SampleActivity extends AppCompatActivity implements View.OnClickListener
{
private CardView mCardView;
private Button mBtnClick;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
mCardView = (CardView) findViewById(R.id.createsub_card);
mBtnClick = (Button) findViewById(R.id.button);
mBtnClick.setOnClickListener(this);
// mCardView.setCardBackgroundColor(getResources().getColorWrongWay(R.color.color_black));
setColor(R.color.color_black);//hex color code id #000000
mCardView.setCardBackgroundColor(getColorWrongWay());// you set like this
}
private int mColor = 0;
private void setColor(int color)
{
mColor = color;
}
private int getColorWrongWay()
{
return mColor;
}
private int getColorCrtWay()
{
return getResources().getColor(mColor);
}
@Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.button:
{
mCardView.setCardBackgroundColor(getColorCrtWay());// should be like this.
}
break;
}
}
}
錯誤道 :
private int getColorWrongWay()
{
return mColor;
}
正確方法:
private int getColorCrtWay()
{
return getResources().getColor(mColor);
}
輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.