Подтвердить что ты не робот

Изменить цвет фона edittext в android

Если я изменил цвет фона моего 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>

Вот как это выглядит:

Image of EditText

4b9b3361

Ответ 1

Что вам нужно сделать, так это создать 9 патч-изображений для edittext и установить это изображение в качестве фона для редактирования текста. Вы можете создать 9 патчей, используя этот веб-сайт

Я прикрепляю образец 9 патча для вашей ссылки. Используйте его как фон edittext, и вы получите представление. Нажмите на изображение и выберите "сохранить изображение как". Когда вы сохраняете изображение, не забудьте указать его расширение как "9.png"

enter image description here

Ответ 2

одна строка ленивого кода:

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

Ответ 3

Здесь лучший способ

Сначала: создайте новый xml файл в res/drawable назовите его 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 copy и предыдущем коде (код 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>

Ответ 4

Я создаю файл 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>

и добавьте стиль ctreated в EditText:

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

Ответ 5

Цвет, который вы используете, белый "#ffffff" белый, попробуйте изменить одно значение в значениях, если хотите, пока не получите нужную ссылку из этой ссылки Цветные кодыи он должен идти хорошо

Ответ 6

Самое простое решение, которое я нашел, - программно изменить цвет фона. Это не требует обработки любых изображений с 9 патчами:

((EditText) findViewById(R.id.id_nick_name)).getBackground()
    .setColorFilter(Color.<your-desi‌​red-color>, PorterDuff.Mode.MULTIPLY);

Источник: другой ответ

Ответ 7

Вы должны использовать стиль вместо цвета фона. Попробуйте найти holoeverywhere, тогда я думаю, что этот поможет вам решить вашу проблему.

Использование holoeverywhere

просто измените некоторые ресурсы 9patch, чтобы настроить внешний вид edittext.

Ответ 8

Для меня этот код работает Поэтому поместите этот код в файл 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>

Ответ 9

Я разработал рабочее решение этой проблемы через 2 дня борьбы, ниже решение идеально подходит для тех, кто хочет изменить только текст редактирования, изменить/переключить цвет через 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 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);

Ответ 10

Это мое рабочее решение

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