2016-11-05 3 views
0

У меня есть проверка на EditText в приложении для Android. Сообщение об ошибке появится, как ожидается, но значок ошибки по умолчанию не отображается.Значок ошибки по умолчанию не отображается для EditText setError

enter image description here

if(users.getText().toString().isEmpty()){ 
     errorNum++; 
     users.setError("Field can not be empty"); 
    } else { 
     users.setError(null); 
    } 

Я также попытался с пользовательским значком, он не работает слишком.

users.setError("Field can not be empty",getDrawable(R.drawable.ic_error_outline_black_24dp)); 

Как получить значок ошибки по умолчанию для проверки

РАСПОЛ файл

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.dinesh.note.MainActivity"> 

<TableLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentStart="true"> 

    <TableRow 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 

     <TextView 
      android:id="@+id/textView7" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 

      android:labelFor="@+id/users" 
      android:text="@string/users" 
android:textAppearance="@android:style/TextAppearance.Widget.TextView" /> 

     <EditText 
      android:id="@+id/users" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:ems="10" 
      android:inputType="number" 
      /> 
    </TableRow> 

    <TableRow 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" > 

     <TextView 
      android:id="@+id/textView4" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:labelFor="@+id/years" 
      android:text="@string/years" 


android:textAppearance="@android:style/TextAppearance.Widget.TextView" /> 

     <EditText 
      android:id="@+id/years" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 


      android:ems="10" 
      android:inputType="number" /> 
    </TableRow> 

    <TableRow 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" > 

     <TextView 
      android:id="@+id/textView5" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:labelFor="@+id/percentage" 
      android:text="@string/percentage" 
      android:textAppearance="@android:style/TextAppearance.Widget.TextView" /> 

     <EditText 
      android:id="@+id/percentage" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 

      android:ems="10" 
      android:inputType="numberDecimal" /> 
    </TableRow> 

    <TableRow 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" > 

     <TextView 
      android:id="@+id/textView6" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:labelFor="@+id/months" 
      android:text="@string/months" 
      android:textAppearance="@android:style/TextAppearance.Widget.TextView" /> 

     <EditText 
      android:id="@+id/months" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 

      android:ems="10" 
      android:inputType="number" /> 
    </TableRow> 
</TableLayout> 

<TextView 
    android:id="@+id/tamount" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentStart="true" 
    android:layout_below="@+id/calculate" 
    android:layout_marginTop="24dp" 
    android:text="@string/tamount" 
    android:textAppearance="@style/TextAppearance.AppCompat.Title" /> 

<TextView 
    android:id="@+id/amount" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentStart="true" 
    android:layout_below="@+id/tamount" 
    android:layout_marginTop="24dp" 
    android:text="@string/amount" 
    android:textAlignment="center" 
    android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large" 
    android:textSize="36sp" 
    android:textColor="@color/colorAccent" /> 

<Button 
    android:id="@+id/calculate" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@color/colorPrimary" 
    android:text="@string/calculate" 
    android:textColor="@android:color/background_light" 
    android:layout_marginTop="227dp" 
    android:onClick="calculateBtn" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentStart="true" /> 
</RelativeLayout> 

стилей XML

<resources> 
<!-- Base application theme. --> 
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> 
    <!-- Customize your theme here. --> 
    <item name="colorPrimary">@color/colorPrimary</item> 
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item> 
    <item name="colorAccent">@color/colorAccent</item> 
</style> 

</resources> 
+1

Можете ли вы разместить файл макета? –

+0

добавил мой файл макета – Dinesh

ответ

1

Я серьезно предлагаю вам рассмотреть современный подход к такого рода вещи по одной причине: с большим количеством пользователей, обновления своих устройств, совместимых назад библиотек из Google уже доступны, чтобы сделать это.

Например, попробуйте: TextInputLayout, который доступен через библиотеку поддержки. Если вы еще не добавили, сделайте это в своем файле app-level build.gradle.

compile 'com.android.support:design:25.0.0' 

Затем в файле макета:

<android.support.design.widget.TextInputLayout 
    android:id="@+id/quoteIdWrapper" 
    android:layout_gravity="start" 
    android:layout_width="match_parent" 
    android:gravity="start" 
    android:layout_height="wrap_content"> 

    <EditText 
     android:id="@+id/quoteId" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:textSize="18sp" 
     android:lines="8" 
     android:layout_gravity="start" 
     android:gravity="top|start" 
     android:minLines="5" 
     android:maxLines="10" 
     android:scrollbars="vertical" 
     android:inputType="textCapSentences|textMultiLine" 
     android:hint="@string/quote_text"/> 

</android.support.design.widget.TextInputLayout> 

С вашего кода, вы можете получить ссылки на обоих пунктов (TextInputLayout & EditText).

Далее, проверить поле EditText и если что-то недействительна, установите следующие атрибуты для TextInputLayout справки:

textInputLayout.setErrorEnabled(true); 
textInputLayout.setError("Your error message"); 

Это будет автоматически сигнализировать с правом цвета (красный часто) к пользователю, что делает его легче знать, что что-то пропущено.

Надеюсь, вы поняли мою идею. Удачи!!

+1

Спасибо за подход .. он сработал .. :) – Dinesh

1

Есть два ways-

Метод 1

Вы можете создать свой собственный класс EditText путем переопределения setError() метод и использовать setCompoundDrawables() метод для отображения значка ошибки.

public class CustomErrorEditText extends EditText { 

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

    @Override 
    public void setError(CharSequence error, Drawable icon) { 
     setCompoundDrawables(null, null, icon, null); 
    } 
} 

Метод 2

Вы должны установить границы на Drawable перед его использованием в setError.

Drawable drawable = getDrawable(R.drawable.ic_error_outline_black_24dp); 
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); 
users.setError("error", drawable); 
+0

Есть ли способ получить значок ошибки по умолчанию? – Dinesh

+0

'setError (String)' даст вам значок по умолчанию –

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