在安卓中更改EditText的背景颜色

31

如果我使用以下代码更改EditText的背景颜色,它看起来像框被缩小了,而且它不保持ICS主题中存在于默认EditText的蓝色底部边框。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#99000000"
    >
    <EditText
        android:id="@+id/id_nick_name"
        android:layout_marginTop="80dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"  
    />
    <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
             android:layout_marginTop="10dip"
             android:layout_marginLeft="20dip"
             android:layout_marginRight="20dip"
            android:orientation="horizontal"
            android:layout_below="@+id/id_nick_name">  
        <Button 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="add"
            android:layout_weight="1"
            />
         <Button 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="cancel"
            android:layout_weight="1"
            />
    </LinearLayout>
</RelativeLayout>

这是它的样子:

EditText的图片

10个回答

42

一行懒人代码:

mEditText.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);

这对于在Holo和Material Design中着色背景非常有效,并且容易实现。 谢谢! 这可能是被接受的答案 - 它保留了视图的原始背景和尺寸,同时改变了其颜色。 - Tom
你是救星! - Sergey Maslov
这个可以运行,但是我应用中的其他EditText保持了这种颜色。 - Georgian Benetatos
1
@GeorgianBenetatos 如果您只想更改特定实例,则应在更改可绘制对象之前进行可变突变:http://android-developers.blogspot.fr/2009/05/drawable-mutations.html - Marc Plano-Lesay

22

这里是最好的方法

第一步:在 res/drawable 中创建一个新的xml文件,名为rounded_edit_text,然后将以下内容粘贴进去:

<?xml version="1.0" encoding="utf-8"?>
<shape  xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#F9966B" />
    <corners
        android:bottomRightRadius="15dp"
        android:bottomLeftRadius="15dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp" />
</shape>

第二步:在res/layout文件夹下,复制并粘贴以下代码(EditText的代码)。

<EditText
    android:id="@+id/txtdoctor"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="@drawable/rounded_edit_text"
    android:ems="10" >
    <requestFocus />
</EditText>

你可以把实心颜色改为你需要的颜色。 - Mohamed Ibrahim
请帮我了解布局如何读取可绘制文件?提前感谢。 - Pravinraj Venkatachalam

12
我创建了 color.xml 文件,用于给我的颜色命名(比如黑色、白色...)。
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
    <color name="white">#ffffff</color>
    <color name="black">#000000</color>
 </resources>

在您的EditText中,设置颜色

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asdsadasdasd"
        android:textColor="@color/black"
        android:background="@color/white"
        />

或在你的style.xml中使用样式:

<style name="EditTextStyleWhite" parent="android:style/Widget.EditText">
    <item name="android:textColor">@color/black</item>
    <item name="android:background">@color/white</item>
</style>

并给EditText添加创建的样式:

 <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asdsadasdasd"
        style="@style/EditTextStyleWhite"
        />

9
你需要做的是创建一个9 patch图片并将其设置为EditText的背景。你可以使用这个网站来创建9 patches。
我附上了一个示例9 patch图片供你参考。将其用作edittext背景,你就会有一个想法。右键单击图像,选择“另存为”。保存图像时不要忘记将扩展名命名为“9.png”。

很酷,它的工作方式就像我预期的那样,唯一需要改变的是图片,以满足我的需求。谢谢。 - Naruto

2
我找到的最简单的解决方案是通过编程方式更改背景颜色。这不需要处理任何9-patch图像:
((EditText) findViewById(R.id.id_nick_name)).getBackground()
    .setColorFilter(Color.<your-desi‌​red-color>, PorterDuff.Mode.MULTIPLY);

来源:另一个答案

你缺少了 .getBackground() 方法 ((EditText) findViewById(R.id.id_nick_name)).getBackground().setColorFilter(Color.<你想要的颜色>, PorterDuff.Mode.MULTIPLY); - Barrie Galitzky

1
你正在使用的颜色是白色 "#ffffff",所以尝试使用其他颜色。如果你想要的话,可以更改值,直到从此链接Color Codes中获得所需的颜色,然后就可以顺利进行了。

0
经过两天的努力,我找到了一个可行的解决方案。以下的解决方案非常适合那些只想更改少量编辑文本、通过Java代码更改/切换颜色,并且想要克服由于使用setColorFilter()方法导致的不同操作系统版本之间的不同行为问题的人们。
    import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatDrawableManager;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import com.newco.cooltv.R;

public class RqubeErrorEditText extends AppCompatEditText {

  private int errorUnderlineColor;
  private boolean isErrorStateEnabled;
  private boolean mHasReconstructedEditTextBackground;

  public RqubeErrorEditText(Context context) {
    super(context);
    initColors();
  }

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

  public RqubeErrorEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initColors();
  }

  private void initColors() {
    errorUnderlineColor = R.color.et_error_color_rule;

  }

  public void setErrorColor() {
    ensureBackgroundDrawableStateWorkaround();
    getBackground().setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(
        ContextCompat.getColor(getContext(), errorUnderlineColor), PorterDuff.Mode.SRC_IN));
  }

  private void ensureBackgroundDrawableStateWorkaround() {
    final Drawable bg = getBackground();
    if (bg == null) {
      return;
    }
    if (!mHasReconstructedEditTextBackground) {
      // This is gross. There is an issue in the platform which affects container Drawables
      // where the first drawable retrieved from resources will propogate any changes
      // (like color filter) to all instances from the cache. We'll try to workaround it...
      final Drawable newBg = bg.getConstantState().newDrawable();
      //if (bg instanceof DrawableContainer) {
      //  // If we have a Drawable container, we can try and set it's constant state via
      //  // reflection from the new Drawable
      //  mHasReconstructedEditTextBackground =
      //      DrawableUtils.setContainerConstantState(
      //          (DrawableContainer) bg, newBg.getConstantState());
      //}
      if (!mHasReconstructedEditTextBackground) {
        // If we reach here then we just need to set a brand new instance of the Drawable
        // as the background. This has the unfortunate side-effect of wiping out any
        // user set padding, but I'd hope that use of custom padding on an EditText
        // is limited.
        setBackgroundDrawable(newBg);
        mHasReconstructedEditTextBackground = true;
      }
    }
  }

  public boolean isErrorStateEnabled() {
    return isErrorStateEnabled;
  }

  public void setErrorState(boolean isErrorStateEnabled) {
    this.isErrorStateEnabled = isErrorStateEnabled;
    if (isErrorStateEnabled) {
      setErrorColor();
      invalidate();
    } else {
      getBackground().mutate().clearColorFilter();
      invalidate();
    }
  }
}

在 XML 中的用途

<com.rqube.ui.widget.RqubeErrorEditText
            android:id="@+id/f_signup_et_referral_code"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toEndOf="@+id/referral_iv"
            android:layout_toRightOf="@+id/referral_iv"
            android:ems="10"
            android:hint="@string/lbl_referral_code"
            android:imeOptions="actionNext"
            android:inputType="textEmailAddress"
            android:textSize="@dimen/text_size_sp_16"
            android:theme="@style/EditTextStyle"/>

以样式添加行

<style name="EditTextStyle" parent="android:Widget.EditText">
    <item name="android:textColor">@color/txt_color_change</item>
    <item name="android:textColorHint">@color/et_default_color_text</item>
    <item name="colorControlNormal">@color/et_default_color_rule</item>
    <item name="colorControlActivated">@color/et_engagged_color_rule</item>
  </style>

Java代码切换颜色

myRqubeEditText.setErrorState(true);
myRqubeEditText.setErrorState(false);

0
你应该使用样式而不是背景颜色。尝试搜索 holoeverywhere,然后我认为这个会帮助你解决问题。 使用 holoeverywhere 只需更改一些 9patch 资源以自定义 edittext 的外观和感觉。

0

对我来说,这段代码是有效的,所以将此代码放入XML文件rounded_edit_text中

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape android:shape="rectangle"> <stroke android:width="1dp" android:color="#3498db" /> <solid android:color="#00FFFFFF" /> <padding android:left="5dp" android:top="5dp" android:right="5dp" android:bottom="5dp" > </padding> </shape> </item> </layer-list>


0

这是我的工作解决方案

View view = new View(getApplicationContext());
view.setBackgroundResource(R.color.background);
myEditText.setBackground(view.getBackground());

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