TextInputLayout 的使用以及style 样式简化代码的编写和后续的修改与维护

一:TextInputLayout 的使用

布局:

 <!--依赖com.android.support:design.XXXX--   注TextInputLayout 里面只能放一个控件>
    <android.support.design.widget.TextInputLayout
        android:id="@+id/phoneLayoutId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


        <android.support.design.widget.TextInputEditText
            android:id="@+id/phoneTextxId"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/username"/>

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

-----------------------------------------------------

代码:

//获得TextInputLayout对象(此对象内部只能有一个EditText)
        phoneLayout = (TextInputLayout) findViewById(R.id.phoneLayoutId);
        //获得TextInputEditText对象(此对象继承EditText)
        phoneText = (TextInputEditText) findViewById(R.id.phoneTextxId);
    }
    //wwww(when,what,where,why)+How
    public void onClick(View v){
        String phone=phoneText.getText().toString();
        if(TextUtils.isEmpty(phone)){
            //显示错误
            phoneLayout.setErrorEnabled(true);
            //设置错误内容
            phoneLayout.setError("phone can not be null");
            return;
        }else{
            //不显示错误
            phoneLayout.setErrorEnabled(false);
        }



结果:

TextInputLayout 的使用以及style 样式简化代码的编写和后续的修改与维护


二:style 样式简化代码的编写和后续的修改与维护

在res/value/style文件中自定义自己的style:

<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>
<style  name="MyBtnStyle">
<item name="android:layout_marginLeft">8dp</item>
<item name="android:layout_marginRight">8dp</item>
<item name="android:background">@drawable/btn_selector_01</item>
    </style>
</resources>


在布局中应用自己的style:

 <Button
            android:id="@+id/logonId"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            style="@style/MyBtnStyle"
            android:text="登录"/>

原本的布局是:

 <Button
            android:id="@+id/enterId"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:background="@drawable/btn_selector_01"

            android:text="登入"/>

假如在布局中有好多的button,这样在后续修改所有的button的中居左居右的距离时,只需要修改style 就可以,而不用一一修改每个button,既简化了代码,又便于维护。


结果:

TextInputLayout 的使用以及style 样式简化代码的编写和后续的修改与维护