自定义属性中使用android原生属性

有时候我们使用自定义属性时,可能会遇到需要使用android已有属性的情况。

比如,大家有遇到过EditText设置右对齐gravity="right"的时候,如果存在hint,那么EditText游标的初始位置会在hint文字的左边的问题吗?

关于这个问题比较通用的一个解决方法,请先瞄一眼这篇文章:解决EditText文字右对齐时光标出现在hint文字的左边的问题

假如我们将这个解决方案封装成一个自定义控件(不贴代码了):
采用FrameLayout布局,EditText和TextView重叠在一起,通过监听EditText的TextChange隐藏和显示TextView。

这个自定义控件在使用上会有什么问题吗?
我们在xml中使用的时候就无法直接设置edittext自身的属性了,只能通过自定义属性设置。 例如:

   <declare-styleable name="CursorCompatEditText">
        <attr name="textColor" format="color|reference"/>
        <attr name="textSize" format="dimension"/>
    </declare-styleable>

    <com.foton.android.widget.CursorCompatEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:textColor="@color/colorPrimary"
            app:textSize="@dimen/font_14"/>

如果我们想设置inputType的属性怎么办,inputType可是有好十几种选择。难道我们都需要在自定义属性上加吗?
当然你可以选择只加上常用的几种,但是这里有更好的解决方式。
就是直接定义android原有的属性。

    <declare-styleable name="CursorCompatEditText">
        <attr name="textColor" format="color|reference"/>
        <attr name="textSize" format="dimension"/>
        <attr name="android:inputType"/>
    </declare-styleable>
    <com.foton.android.widget.CursorCompatEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            app:textColor="@color/colorPrimary"
            app:textSize="@dimen/font_14" />
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CursorCompatEditText);
int inputType = a.getInt(R.styleable.CursorCompatEditText_android_inputType, EditorInfo.TYPE_NULL);
a.recycle();

可以看到,CursorCompatEditText明明是继承FrameLayout,但是也可以使用inputType属性了,而在自定义控件中也获取inputType也和自定义属性的方式没有区别。(一开始我还想方设法的通过com.android.interval.R.styleable.TextView_inputType获取……)

最后补充下:
其实这样自定义View使用起来还是稍微有点麻烦。
推荐直接自定义View继承EditText,上面推荐文章的评论中有实现。
也可以参考Design包中TextInputLayout的方式(包裹一个EditText,看起来很像装饰者模式)
这样就不需要大量的使用自定义属性了。

猜你喜欢

转载自blog.csdn.net/u010386612/article/details/79533057