Scheming with the Coco and Android

February 27 2013
This example shows how you can change the color of a word in a EditText using a ForegroundColorSpan. BlueWord.zip
I created the outline for this project like this:

android create project --target "Google Inc.:Google APIs:17" --name BlueWord --path C:/Users/Earl/Documents/BlueWord --activity BlueWord --package org.nuts4cocos.blueword

This is what I changed:

*** mail.xml ***

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <EditText android:id="@+id/editText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
</LinearLayout>

*** BlueWord.java ***

package org.nuts4cocos.blueword;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.widget.EditText;

public class BlueWord extends Activity {
  
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    ForegroundColorSpan blueSpan=new ForegroundColorSpan(Color.BLUE);;
    EditText editText=(EditText)findViewById(R.id.editText);
    String string="foo goo loo";
    int begin=string.indexOf("goo");
    int end=string.indexOf(" ", begin);
    Spannable spannable=new SpannableString(string);
    spannable.setSpan
    (blueSpan, begin, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    editText.setText(spannable);
  }
}
§447 · By · February 27, 2013 ·


Leave a Reply