Saturday, November 27, 2010

Android Color Spinner

A quick hack for choosing colors with a Spinner. The color names are not displayed, instead the values of a string array are parsed as color values.




Lets start with the spinner declaration:

Spinner spinner = (Spinner) findViewById(R.id.color_spinner);
  ArrayAdapter adapter = new ArrayAdapter(this,
  R.layout.color_spinner_item, new String[] { "#F5F6F6",
    "#FFC0CB", "#FF0000", "#C00000" });
  adapter.setDropDownViewResource(R.layout.color_spinner_dropdown_item);
  spinner.setAdapter(adapter);

Next thing is the layout definitions for the item and the dropdown item:

color_spinner_dropdown_item.xml
<view xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@android:id/text1"
       class="net.eggeral.CheckedColorTextView" 
       style="?android:attr/spinnerDropDownItemStyle"
       android:singleLine="true"
       android:layout_width="fill_parent"
       android:layout_height="?android:attr/listPreferredItemHeight"
       android:ellipsize="marquee" />

color_spinner_item.xml
<view
  class="net.eggeral.ColorTextView" 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"/>

And two custom views for item and dropdown item:

CheckedColorTextView.java
package net.eggeral;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.CheckedTextView;

public class CheckedColorTextView extends CheckedTextView {
public CheckedColorTextView(Context context) {
super(context);
}

public CheckedColorTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
public void onDraw(Canvas canvas) {
int color = Color.parseColor(getText().toString());
Paint paint = new Paint();
paint.setColor(color);
setTextColor(color);

canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), 5, 5,
paint);
super.onDraw(canvas);
}
}

ColorTextView.java
package net.eggeral.marmind;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.TextView;

public class ColorTextView extends TextView {
public ColorTextView(Context context) {
super(context);
}

public ColorTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
public void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.parseColor(getText().toString()));

canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), 5, 5,
paint);
}
}
Post a Comment