[关闭]
@cxm-2016 2016-08-29T07:01:43.000000Z 字数 1799 阅读 2056

创建具有错误提示的输入框

android no


如何添加

1,在你的build.gradle添加如下组件

  1. dependencies {
  2. compile 'com.android.support:appcompat-v7:X.X.X' // where X.X.X version
  3. compile 'com.android.support:design:X.X.X' // where X.X.X version
  4. }

2,确保你的activity继承自android.support.v7.app.AppCompatActivity

  1. public class MainActivity extends AppCompatActivity {
  2. ...
  3. }

3,声明你的EditText所在的布局文件,并且使其被TextInputLayout包括

  1. <android.support.design.widget.TextInputLayout
  2. android:id="@+id/inputLayout"
  3. android:layout_width="match_parent"
  4. android:layout_height="wrap_content"
  5. app:errorEnabled="true">
  6. <EditText
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:hint="@string/First_name" />
  10. </android.support.design.widget.TextInputLayout>

4,显示或者隐藏错误消息

  1. TextInputLayout inputLayout = (TextInputLayout) findViewById(R.id.inputLayout);
  2. inputLayout.setError("First name is required"); // show error
  3. inputLayout.setError(null); // hide error

在TextInputLayout中声明app:errorEnabled="ture"属性就可以在EditText的下面显示错误信息了.除了使用TextInputLayout包裹TextView之外,我们还能后直接使用TextInputEditText控件

如何自定义样式

1,在你的style.xml文件中声明样式如下

  1. <!--Error label text style-->
  2. <style name="MyErrorText" parent="TextAppearance.AppCompat.Small">
  3. <item name="android:textColor">@color/pink</item>
  4. </style>
  5. <!--Input field style-->
  6. <style name="MyEditText" parent="Theme.AppCompat.Light">
  7. <item name="colorControlNormal">@color/indigo</item>
  8. <item name="colorControlActivated">@color/pink</item>
  9. </style>

2,在你的TextInputLayout中通过app:errorTextApperance属性和通过给EditText设置android:theme属性来完成

  1. <android.support.design.widget.TextInputLayout
  2. android:layout_width="match_parent"
  3. android:layout_height="wrap_content"
  4. app:errorTextAppearance="@style/MyErrorText"
  5. app:errorEnabled="true">
  6. <EditText
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:hint="@string/Title"
  10. android:theme="@style/MyEditText" />
  11. </android.support.design.widget.TextInputLayout>
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注