Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> EditText輔助控件—TextInputLayout

EditText輔助控件—TextInputLayout

編輯:關於Android編程

1.介紹

TextInputLayout是一個用於在EditText上顯示Floating效果的輔助控件。

效果圖如下:

\

2.使用方法

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);
    }
}
布局文件



    

    

        

    

    

        

    

3.注意

1>在EditText中設置textColorHint屬性是沒有效果的,textColorHint會根據Theme的顏色來顯示,只能通過設置Activity的Theme來更改hint的顏色。
GitHub地址:https://github.com/alidili/DesignSupportDemo  
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved