Search code examples
javaandroidcolorshex

I want to convert some Color Hex in Andorid Studio.But, some of them throw an error?How to fix it?


I retrive some data from api.stackoverflow using Retrofit. Here some of them: #FFF, #666, #5A8F53, #1B8FBB. And then I want to use them textView.setBackgroundColor property. So, I use Color.parseColor() method.But, there is an error unidentified color. How to solve this problem?

    @Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View view=layoutInflater.inflate(R.layout.p203customrow,parent,false);   
    ImageView imageViewP203= (ImageView)view.findViewById(R.id.imageViewP203);
    TextView textViewNameP203= (TextView)view.findViewById(R.id.textViewNameP203);
    TextView textViewSiteUrlP203= (TextView)view.findViewById(R.id.textViewSiteUrlP203);

    P203ApiStyle.P203ItemsObjects p203ItemsObjects= p203ItemsObjectsList.get(position);
    Map<String,String> mapStyle=p203ItemsObjects.getStyling();
    String backgroundColor= mapStyle.get("tag_background_color");
    String foregroundColor= mapStyle.get("tag_foreground_color");

    textViewNameP203.setText("Name="+p203ItemsObjects.getName()+" BackgroundColor="+backgroundColor);  
//one result--> Name=Webmasters BacgroundColor=#FFF
    textViewSiteUrlP203.setText("SiteUrl=" + p203ItemsObjects.getSite_url() + " BackgroundColor=" + foregroundColor);
 //one result-->SiteUrl=The url BackgoundColor=#1B8FBB

//when I uncommet to this block that error occurs...
  /*  textViewNameP203.setBackgroundColor(Color.parseColor(backgroundColor));
    textViewSiteUrlP203.setBackgroundColor(Color.parseColor(foregroundColor));*/

    Picasso.with(context).load(p203ItemsObjects.getIcon_url()).resize(100, 100).into(imageViewP203);
    return view;
}

Solution

  • As i mentioned in the comment , In your code , you are using websafe color instead of HEX color.

    A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue) hexadecimal integers specify the components of the color. All values must be between 00 and FF.

    For example, the #0000FF value is rendered as blue, because the blue component is set to its highest value (FF) and the others are set to the lowest value (00).

    So you must change your websafe colors to hex colors. In your code , please change #FFF to #FFFFFF and #666 to #666666 .

    please check here to see the available colors sorted by name.

    and check here to see the material color codes.