Android 4上EditText的子类看起来与普通EditText不同

5
这是我在开发实际应用程序时发现的一个“错误”,但我创建了一个空项目来重现它。
我有以下布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:id="@+id/root"
    android:orientation="vertical"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <com.example.test.testapp.MyEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


</LinearLayout>

MyEditText的外观如下:
public class MyEditText extends EditText {

    public MyEditText(Context context){
        super(context);
    }

    public MyEditText(Context context, AttributeSet attrs){
        super(context, attrs);
    }


    public MyEditText(Context context, AttributeSet attrs, int defStyle){
        super(context, attrs, defStyle);
    }


}

我的styles.xml文件除了主题之外是空的

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

</resources>

我希望MyEditText看起来像普通的EditText,在Android 5.0上它是这样的,但在Android 2.3.7、Android 4.1.3或Android 4.4.4上不是。在这些Android版本中,EditText的颜色不同,普通的有一个青色的下划线,而自定义的有一个黑色的下划线:

enter image description here

enter image description here

为什么会出现这种情况,我该如何避免?

编辑/更新:

Google似乎已经通过引入AppCompatEditText类等方式在支持库中解决了这个问题。(链接)
2个回答

6

为什么会发生这种情况?

因为您正在使用AppCompat。引用有关此主题的博客文章

问:为什么我的EditText(或其他上面列出的小部件)在我的Lollipop之前的设备上没有正确着色?

答:AppCompat中的小部件着色通过拦截任何布局膨胀并插入其位置的特殊着色感知版本的小部件来工作。对于大多数人来说,这将很好地工作,但我可以想到一些情况,在这些情况下,这不起作用,包括:

  • 您拥有自己的小部件自定义版本(即,您已扩展EditText)
  • 您正在创建EditText而没有LayoutInflater(即,调用new EditText())。

因此,这种行为是可以预期的。AppCompat后移提供了一些轻量级的着色后移,但它不会处理所有情况。

如何防止它发生?

随意地说,要么:

  • 不要创建EditText的子类,或者

  • 在运行AppCompat时,查找色调并自行确定如何应用它,可能需要检查AppCompat源代码(假设可用-我没有寻找),或者

  • 不使用AppCompat,并查看在Android 5.0+设备上使用Theme.Material是否按预期进行着色

未来的AppCompat可能会提供某种系统,使子类能够参与着色过程。还可能有其他解决方案-这些是我想到的。


哇,你已经准备好这个答案了吗?:) 非常感谢! - fweigl
@Ascorbin: "哇,你已经准备好这个答案了吗?" -- 好吧,这是半个引用,可以省去打字。 :-) 我需要自己看一下我的第二个选项,因为我有一个EditText的子类(https://github.com/commonsguy/cwac-richedit),它也会遇到同样的问题。 - CommonsWare

5
实际上,这个被接受的答案所得出的结论并不完全正确(现在)。你应该使用AppCompat,但需要意识到,在布局膨胀期间,AppCompat将用AppCompatEditText替换您的EditText。同样的过程也会发生在其他一些UI元素上,比如Switch、CheckBox等。谷歌这样做是为了尽可能少地从用户那里进行代码更改,以便将Material design的外观和感觉推广到各个方面。

如果要创建EditText子类,则应创建AppCompatEditText子类(android.support.v7.widget.AppCompatEditText)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接