• No results found

CREATING CUSTOM VIEWS

In document Android (Page 80-86)

THE VIEW CLASS

CREATING CUSTOM VIEWS

The concept of custom views can really be broken out into two sections: extending an existing view and creating an entirely new one. I’ve rarely, in my career as an Android developer, created a completely custom view, so we’ll skip over it here. The Android SDK documentation has directions for the industrious among you who want to roll your very own from scratch. However, even if you plan to extend an Android view, you must create a new class that extends the existing view. Here’s how you’d go about it.

DECLARING THE NEW CLASS

The first step in declaring a custom view is to create the class. Android allows you to subclass any of its existing UI objects simply by extending an existing class. The declaration looks like this:

public class CustomTextView extends TextView{

public CustomTextView(Context context) { super(context);

} }

THE VIEW CLASS 65

ptg7794906 That’s all it takes to create a custom text view. However, since there’s about as

much custom in this custom text view as there is beef in fast-food tacos, I’ll add something simple to set it apart.

EXTENDING A VIEW

Although Android’s layouts and views are powerful and versatile, there are times when they just won’t do exactly what you want. Fortunately, their functionality is easy to extend. To demonstrate, I’ve written a custom text view that changes the color of every letter in the text to be displayed onscreen. While this isn’t the most practical use case, it will show how simple it is to implement your own behavior.

CUSTOMIZING AN EXTENDED VIEW

You’d be amazed at how much code it takes to correctly render text to the screen.

Android’s TextView.java class is nearly 5000 lines of code. But thanks to the ability to extend a class, you can use all the complex layout code and customize only the part that appeals to you. In this example, I catch the text as it changes and add a new ForegroundColorSpan for each letter in the new string. First, I declare an array of colors.

public class CustomTextView extends TextView{

int colorArray[] = new int[]{Color.WHITE, Color.RED,

Color.YELLOW, Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN, Color.DKGRAY};

ptg7794906 Now, each time the text changes, I add a new ForegroundColorSpan for each letter.

protected void onTextChanged(CharSequence text, int start, int before, int after ) {

//Keep the view from getting into an infinite loop if(selfChange){

I make sure I don’t get stuck in an infinite loop (with the change in color trig-gering another onTextChanged call, which changes the color again, which changes the color. . .you get the idea). Next comes the code that changes the colors:

SpannableStringBuilder builder = new SpannableStringBuilder(text);

builder.clearSpans();

ForegroundColorSpan colorSpan;

int color;

for(int i=0; i < text.length(); i++){

//pick the next color

color = colorArray[i%colorArray.length];

//Create the color span

colorSpan = new ForegroundColorSpan(color);

//Add the color span for this one char builder.setSpan(colorSpan,

ptg7794906 Again, not very complex, but then neither is extending an existing view class.

Also, be warned that this code will clear any formatting that may have already been set on the text. (At this point, don’t stress too much about how spans and SpannableStringBuilders work. In short, they’re blocks of formatting that you can drop over strings. Check the Android SDK documentation for more info.) If you’re looking for a coding challenge, try creating an array with every possible RGB hex color value and cycling through that array.

USING YOUR EXTENDED VIEW

Just as with any other Android view, you can create a new instance of it at runtime in your Java code or pre-declare it in your XML layout file. Here’s how you can use it in your activity:

There’s nothing you haven’t seen before going on here. I’m creating a new instance of my view, setting the text for it, and then setting it as the main view for my activity. You could also put it inside a layout object with other views. It’s also possible to add this custom view to an XML-described layout. But before you can start declaring your custom view in an XML file, you need to create the full suite of View constructors. Your custom view should look something like this:

public class CustomTextView extends TextView{

ptg7794906

//Rest of the class omitted for brevity }

When Android parses your XML layout and creates your view, it needs to pass an attribute set to the constructor because this contains all the layout informa-tion, text, and whatever else you’ve added that starts with android. If you forget to add these, everything will compile, but it will show the Unexpected Force Close window of doom when you try to draw the screen.

Now that you have the correct constructors, it’s possible to create and lay out your custom view within XML. In the code to follow, I’ve added a single instance of the rainbow animating custom text display.

<?xml version=”1.0” encoding=”utf-8”?>

ptg7794906 As you can see, adding a custom text view to your XML layouts only requires

you to use the full Java package and class name. You can also see that because CustomTextView extends TextView, I can use any attribute (like android:text) that I would use with one of Android’s TextViews.

Congrats, you’ve created a custom Android view to do your bidding in only a few lines of code, you’ve displayed it to the screen, and you even have the capability to include it within a more complex layout system. Google has done a fantastic job of allowing developers to extend the functionality of basic building blocks included in the Android SDK. If this extended custom view leaves you wanting more of a challenge, try making a simple text view that does exactly the same things as the extended view. You’ll need to explore the onMeasure and onDraw methods of your own view. Go ahead, check it out, I’ll be here when you get back.

ptg7794906

In document Android (Page 80-86)