个人知识总结:View篇--TextView

2019-04-18  本文已影响0人  佐手邊倖冨

Displays text to the user and optionally allows them to edit it. A TextView is a complete text editor, however the basic class is configured to not allow editing; see for a subclass that configures the text view for editing.

这是Google官方对TextView的一个介绍:向用户显示文本,并允许用户编辑文本。TextView是一个完整的文本编辑器,但是基本类配置为不允许编辑;查看配置用于编辑的文本视图的子类。

常用属性

这里初略的列举出了TextView的属性值,当然那些常识性的属性就没有列举了,还有一些属性即使设置了也没有效果,只有在TextView的子类EditText里面才会起作用,像输入法以及软键盘相关的一些属性,在TextView上面设置都是没有用的。基本上常用的一些功能,都可以在xml中直接配置并实现,像跑马灯滚动,文本左右的图片等。

一个滑动小功能

下面介绍一个TextView文本上下滑动功能,可能有的人会说了,其实可以直接使用EditText,设置成不可编辑就可以了,这也是一种解决办法,我们这里用TextView实现。只需要设置一个属性就可以了(当然前提是你的TextView是固定高度的) ,这个属性只能通过Java语句设置,不能在xml文件里面设置,
textView.setMovementMethod(ScrollingMovementMethod.getInstance());
当然也可以在xml里面去定义滑块的显示和样式。

TextView的常用子类
Button

A user interface element the user can tap or click to perform an action.

Button去Api里面看源码,就会发现他非常的简单,就只是在继承TextView的同时,在构造方法中给与了Button特有的style,

public Button(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.buttonStyle);
    }

没有什么额外的操作,也就在8.0以后加入了onResolvePointerIcon方法,手指点击后的一个动态效果。

CheckBox

A checkbox is a specific type of two-states button that can be either checked or unchecked.

CheckBox和Button基本上是一样的,都是在构造方法中给了一个CheckBox特有的style,别的也没有什么特殊的操作。

public CheckBox(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.checkboxStyle);
    }
EditText

This is supposed to be a very thin veneer over TextView. Do not make any changes here that do anything that a TextView with a key listener and a movement method wouldn't do!

EditText也和Button,CheckBox一样,在构造方法中给与了EditText特有的style,

public EditText(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.editTextStyle);
    }

所不同的是,EditText里面还自动集成了复制,全选复制的功能,并将文本采集到粘贴板中。

 /**
     * Convenience for {@link Selection#setSelection(Spannable, int, int)}.
     */
    public void setSelection(int start, int stop) {
        Selection.setSelection(getText(), start, stop);
    }

    /**
     * Convenience for {@link Selection#setSelection(Spannable, int)}.
     */
    public void setSelection(int index) {
        Selection.setSelection(getText(), index);
    }

    /**
     * Convenience for {@link Selection#selectAll}.
     */
    public void selectAll() {
        Selection.selectAll(getText());
    }

    /**
     * Convenience for {@link Selection#extendSelection}.
     */
    public void extendSelection(int index) {
        Selection.extendSelection(getText(), index);
    }

当然EditText还有其他的功能,但是这些功能都可以最开始提到的TextView的属性值一一实现。

TextView肯定还有其他的子类,但是我们通常使用的也就只有这三种,其他的就不做介绍。

上一篇 下一篇

猜你喜欢

热点阅读