2016-09-16 2 views
6

enter image description here Я создал EditText внутри TextInputLayout. Я устанавливаю drawableLeft в EditText во время выполнения в моем коде, но как только я добавляю drawableLeft, плавающий подсказку внутри TextInputLayout сдвигается вправо, оставляя пространство равным ширине. Но я не хочу этого места в подсказке, так что помогите мне решить это!Добавление drawableLeft в EditText сдвигает подсказку вправо, если edittext находится внутри TextInputlayout

+0

пожалуйста, напишите ваш XML –

+0

Использование _setCompoundDrawablePadding_ – Piyush

ответ

18

TextInputLayout использует вспомогательный класс - CollapsingTextHelper - для управления текстом подсказки. Экземпляр этого помощника является закрытым, и ни один из атрибутов, связанных с его компоновкой, не отображается, поэтому нам нужно будет немного подумать, чтобы получить к нему доступ. Кроме того, его свойства устанавливаются и пересчитываются каждый раз, когда выкладывается TextInputLayout, поэтому имеет смысл подкласс TextInputLayout, переопределить его метод onLayout() и внести в него наши настройки.

import android.content.Context; 
import android.graphics.Rect; 
import android.support.design.widget.TextInputLayout; 
import android.util.AttributeSet; 
import java.lang.reflect.Field; 
import java.lang.reflect.InvocationTargetException; 
import java.lang.reflect.Method; 

public class CustomTextInputLayout extends TextInputLayout { 
    private Object collapsingTextHelper; 
    private Rect bounds; 
    private Method recalculateMethod; 

    public CustomTextInputLayout(Context context) { 
     this(context, null); 
    } 

    public CustomTextInputLayout(Context context, AttributeSet attrs) { 
     this(context, attrs, 0); 
    } 

    public CustomTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 

     init(); 
    } 

    @Override 
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 
     super.onLayout(changed, left, top, right, bottom); 

     adjustBounds(); 
    } 

    private void init() { 
     try { 
      Field cthField = TextInputLayout.class.getDeclaredField("mCollapsingTextHelper"); 
      cthField.setAccessible(true); 
      collapsingTextHelper = cthField.get(this); 

      Field boundsField = collapsingTextHelper.getClass().getDeclaredField("mCollapsedBounds"); 
      boundsField.setAccessible(true); 
      bounds = (Rect) boundsField.get(collapsingTextHelper); 

      recalculateMethod = collapsingTextHelper.getClass().getDeclaredMethod("recalculate"); 
     } 
     catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException e) { 
      collapsingTextHelper = null; 
      bounds = null; 
      recalculateMethod = null; 
      e.printStackTrace(); 
     } 
    } 

    private void adjustBounds() { 
     if (collapsingTextHelper == null) { 
      return; 
     } 

     try { 
      bounds.left = getEditText().getLeft() + getEditText().getPaddingLeft(); 
      recalculateMethod.invoke(collapsingTextHelper); 
     } 
     catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

Этот пользовательский класс является подходящей заменой для регулярного TextInputLayout, и вы будете использовать его таким же образом. Например:

<com.mycompany.myapp.CustomTextInputLayout 
    android:id="@+id/text_input_layout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:hint="Model (Example i10, Swift, etc.)" 
    app:hintTextAppearance="@style/TextLabel"> 

    <android.support.design.widget.TextInputEditText 
     android:id="@+id/edit_text" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:drawableLeft="@drawable/bmw" 
     android:text="M Series" /> 

</com.mycompany.myapp.CustomTextInputLayout> 

screenshot

+0

Его не работает теперь возвращается ошибка ** CollapsingTextHelper не является публичной в android.support.design.widget; невозможно получить из внешнего пакета ** –

+0

Просто удалите 'CollapsingTextHelper'' import' в верхней части класса. На самом деле это не используется нигде в этом примере. Я просто забыл очистить импорт, прежде чем я разместил, по-видимому. –

+1

Спасибо за его работу. –

-1

Да, это общая проблема, с которой я столкнулся в последнее время. Я решил ее с помощью простого кода одной строки: Поместите отступы между вашим подсказкой и drawbleleft с помощью drawble padding. Если вы добавляете drawble во время выполнения, просто добавьте drawblepadding в xml перед рукой или вы можете динамически добавлять отложенную прокладку.

-1
editText.setCompoundDrawablePadding(your padding value); 

Попробуйте и дайте мне знать. Это сработало для меня.

Смежные вопросы