web-dev-qa-db-fra.com

Changer la couleur de fond dans Android

Si je change la couleur d'arrière-plan de ma EditText à l'aide du code ci-dessous, il semble que la boîte soit réduite et qu'elle ne conserve pas le thème ICS d'une bordure inférieure bleue qui existe pour une EditText par défaut.

<?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>

Voici à quoi cela ressemble:

Image of EditText

26
Naruto

Ce que vous devez faire est de créer une image de 9 correctifs pour edittext et de définir cette image comme arrière-plan de texte modifié. Vous pouvez créer 9 correctifs en utilisant this website

Je vous joins un exemple de 9 patch pour votre référence.Utilisez-le comme arrière-plan edittext pour obtenir une idée.Cliquez à droite sur l'image et sélectionnez "enregistrer l'image sous". Lorsque vous enregistrez l'image, n'oubliez pas de lui attribuer l'extension "9.png"

enter image description here

9
Basim Sherif

une ligne de code paresseux:

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

Voici le meilleur moyen 

Premièrement: créez un nouveau fichier xml dans res/drawable et nommez-le rounded_edit_text puis collez ceci: 

<?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>

Deuxièmement: dans res/layout copy et past code suivant (code de 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>
17
Mohamed Ibrahim

Je crée un fichier color.xml, pour nommer mon nom de couleur (noir, blanc ...)

 <?xml version="1.0" encoding="utf-8"?>
 <resources>
    <color name="white">#ffffff</color>
    <color name="black">#000000</color>
 </resources>

Et dans votre EditText, définissez la couleur

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

ou utilisez stylein 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>

et ajoutez un style traité à EditText:

 <EditText
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:text="asdsadasdasd"
        style="@style/EditTextStyleWhite"
        />
11
RN3KK Nick

La solution la plus simple que j'ai trouvée consiste à modifier la couleur de fond par programme. Ceci ne pas nécessite de traiter avec des images de 9 correctifs:

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

Source: autre réponse

1
Michael Herrmann

La couleur que vous utilisez est le blanc "#ffffff" est le blanc, essayez donc un autre changement dans les valeurs si vous le souhaitez jusqu'à ce que vous obteniez votre besoin par ce lien Codes de couleurs .__ et ça devrait aller bien

1
Cobra47

Pour moi, ce code ça marche Alors, mettez ce code dans le fichier 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
Aziz

Vous devez utiliser le style au lieu de la couleur d'arrière-plan. Essayez de chercher à holoeverywhere alors je pense que celui-ci vous aidera à résoudre votre problème

Utilisation de holoeverywhere

il suffit de modifier certaines des ressources 9patch pour personnaliser l'aspect et la convivialité d'edittext.

0
KaHeL

J'ai travaillé sur une solution de travail à ce problème après 2 jours de lutte. La solution ci-dessous est parfaite pour ceux qui souhaitent modifier quelques textes d'édition, modifier/activer/désactiver la couleur via du code Java et souhaitent résoudre les problèmes de comportement différent selon les versions de système d'exploitation en raison de l'utilisation de la méthode 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();
    }
  }
}

Utilisations en 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"/>

Ajouter des lignes dans le style

<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>

Code Java pour changer de couleur

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