简体   繁体   English

如何在Android中创建我们自己的自定义文本视图?

[英]How to create our own custom text view in Android?

How to create our own custom text view in Android? 如何在Android中创建我们自己的自定义文本视图? I want to set different colors for the textview font. 我想为textview字体设置不同的颜色。

Like eldarerathis commented, it's a bit overkilled if you would create a custom TextView just for changing the text color. 就像eldarerathis所评论的那样,如果您仅创建用于更改文本颜色的自定义TextView,则有点过头了。

Nonetheless, here is a tutorial on how to create a custom TextView. 尽管如此, 这里还是有关如何创建自定义TextView 的教程

Building Custom component on Android developer is also a good read, in fact, I'd encourage you to read through it first. 在Android开发人员上构建自定义组件也是一本好书,实际上,我建议您先通读它。

The summarize 3 steps: 总结3个步骤:

  1. Extend an existing View class or subclass with your own class. 用您自己的类扩展现有的View类或子类。
  2. Override some of the methods from the superclass. 重写超类中的某些方法。 The superclass methods to override start with 'on', for example, onDraw(), onMeasure(), and onKeyDown(). 要覆盖的超类方法以“ on”开头,例如onDraw(),onMeasure()和onKeyDown()。 This is similar to the on... events in Activity or ListActivity that you override for lifecycle and other functionality hooks. 这类似于为生命周期和其他功能挂钩重写的Activity或ListActivity中的on ...事件。
  3. Use your new extension class. 使用新的扩展类。 Once completed, your new extension class can be used in place of the view upon which it was based. 完成后,可以使用新的扩展类来代替其基于的视图。

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. 因此,您随时可以全局更改TextView的颜色。

If all you want to do is set a text color you can use the textColor attribute. 如果您只想设置文本颜色,则可以使用textColor属性。

<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="MyText"
android:textColor="#FFFFFF"
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM