Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

EditText 好搭檔:TextInputLayout 浮動標籤控制項用法

編輯:關於 Android 程式設計

一、這是什麼

TextInputLayout 是 Design Support Library 提供的一個輔助控制項,作用是讓 EditText 的提示文字在獲得焦點、開始輸入時「浮」到框線上方,形成 Material Design 的浮動標籤效果。它同時還能顯示錯誤訊息。

效果如下:

二、怎麼用

用法很直觀:用 TextInputLayout 包住 EditText,設定提示文字時改用 setHint(),並透過 getText() 之外的 getEditText() 取得內部的 EditText。

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by yangle on 2016/7/28.
 */
public class TextInputLayoutActivity extends AppCompatActivity {

    @Bind(R.id.layout_account) TextInputLayout layoutAccount;
    @Bind(R.id.layout_password) TextInputLayout layoutPassword;

    private EditText mAccount;
    private EditText mPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_textinput_layout);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        // 設定提示文字
        layoutAccount.setHint("Username");
        layoutPassword.setHint("Password");

        // 透過 getEditText() 取得內部的 EditText
        mAccount = layoutAccount.getEditText();
        mPassword = layoutPassword.getEditText();

        mAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (s.length() > 5) {
                    // 顯示錯誤提示
                    layoutAccount.setError("Username Error");
                    layoutAccount.setErrorEnabled(true);
                } else {
                    layoutAccount.setErrorEnabled(false);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 點擊空白處時收起軟鍵盤
        InputMethodManager inputMethodManager =
                (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(mAccount.getWindowToken(), 0);
        inputMethodManager.hideSoftInputFromWindow(mPassword.getWindowToken(), 0);
        return super.onTouchEvent(event);
    }
}

對應的布局檔:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/color_E3E3E3"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="100dp"
        android:text="Welcome"
        android:textColor="@color/color_333333"
        android:textSize="35sp" />

    <TextInputLayout
        android:id="@+id/layout_account"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </TextInputLayout>

    <TextInputLayout
        android:id="@+id/layout_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword" />
    </TextInputLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="18dp"
        android:layout_marginRight="18dp"
        android:layout_marginTop="20dp"
        android:text="Login"
        android:textSize="18sp" />
</LinearLayout>

三、實務上會踩到的細節

提示文字顏色不受 textColorHint 控制。在 EditText 上直接設定 android:textColorHint 是沒有效果的,浮動標籤的顏色會跟著 Theme 走。要改只能改 Activity 的 Theme:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:textColorHint">@color/color_333333</item>
</style>

另外兩個實務提醒:一是 setErrorEnabled(true) 必須先呼叫,後續 setError 才看得到訊息,而且錯誤文字會佔用額外的高度,布局時要預留空間避免跳動;二是 TextInputLayout 必須正確包住 EditText 才會生效,兩者平級並不會有效果。

GitHub 範例專案:https://github.com/alidili/DesignSupportDemo

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved