在edittext中为文本指定文本颜色

Cha*_*nya 19 android android-widget

如何通过扩展它来为Edittext中的文本指定不同的颜色.

C. *_*ung 19

您可以通过添加android:textColor如下更改文本颜色:

<EditText
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="#f00" />
Run Code Online (Sandbox Code Playgroud)


Bud*_*ril 13

使用跨度:

TextView textView = (TextView)findViewById(R.id.mytextview01);
Spannable WordtoSpan = new SpannableString("partial colored text");        
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(WordtoSpan);
Run Code Online (Sandbox Code Playgroud)


Atu*_*lic 7

我知道这是一个非常古老的问题,但由于这是我在搜索时得到的第一个问题,我想补充一个答案,以便将来的读者能够得到它们.

我们可以在styles.xml文件中创建自己的自定义样式,除了textColor之外还有许多其他属性,并应用于我们的EditText.

在styles.xml中添加它,

<style name="MyEditTextstyle">
    <item name="android:textColor">@color/dark_blue</item>
    <item name="android:background">@drawable/my_custom_edittext_bg</item>
    <item name="android:layout_marginTop">5dp</item>
    <item name="android:layout_marginBottom">5dp</item>
    //many more per requirement
</style>
Run Code Online (Sandbox Code Playgroud)

然后只需将此样式应用于EditText,

<EditText
    style="@style/MyEditTextstyle" //here
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:hint="Item Name"
    android:padding="10dp" >
    <requestFocus />
</EditText>
Run Code Online (Sandbox Code Playgroud)

简单,对.:)重要的是,如果需要,我们可以将相同的东西应用于任何EditText.:)


小智 6

我在 style.xml 文件中使用 textColor 属性时遇到问题:

        <item name="android:textColor">@color/white</item>
Run Code Online (Sandbox Code Playgroud)

对我来说,editTextColor 有效:

        <item name="android:editTextColor">@color/white</item>
Run Code Online (Sandbox Code Playgroud)


liv*_*ove 5

要以编程方式更改它,请在 color.xml 文件中添加颜色

颜色.xml:

<resources>
    <color name="colorText">#424242</color>
Run Code Online (Sandbox Code Playgroud)

并像这样引用它:

myEditText.setTextColor(ContextCompat.getColor(this, R.color.colorText));
Run Code Online (Sandbox Code Playgroud)