How to create our own custom text view in Android?
How to create o开发者_C百科ur own custom text view in Android? I want to set different colors for the textview font.
Whatever you want:
public class SimpleTextView extends TextView
{
private static int color=Color.RED;
public SimpleTextView(Context context)
{
super(context);
this.setTextColor(color)
}
public SimpleTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
this.setTextColor(color)
}
public SimpleTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
this.setTextColor(color)
}
public static void setGlobalColor(int gcolor)
{
color=gcolor;
}
}
So anytime you can change color of your TextViews globally.
Like eldarerathis commented, it's a bit overkilled if you would create a custom TextView just for changing the text color.
Nonetheless, here is a tutorial on how to create a custom TextView.
Building Custom component on Android developer is also a good read, in fact, I'd encourage you to read through it first.
The summarize 3 steps:
- Extend an existing View class or subclass with your own class.
- Override some of the methods from the superclass. The superclass methods to override start with 'on', for example, onDraw(), onMeasure(), and onKeyDown(). This is similar to the on... events in Activity or ListActivity that you override for lifecycle and other functionality hooks.
- Use your new extension class. Once completed, your new extension class can be used in place of the view upon which it was based.
If all you want to do is set a text color you can use the textColor attribute.
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="MyText"
android:textColor="#FFFFFF"
/>
精彩评论