这篇博客带来Android M 里面的TextInputLayout和Snackbar的使用,及简单介绍。
首先我们必须更新sdk,引入Android M:
compile 'com.android.support:design:22.2.0'
TextInputLayout
官方简介:
该控件解决的问题:
该控件是用于EditView输入框的,主要解决之前EditView在获得焦点编辑时hint属性提示语消失,这一点在一个页面有多个EditView输入框的时候不是很好,因为很有可能用户在输入多个EditView之后,不知道当前EditView需要输入什么内容。
以上是运行在4.1模拟机上的效果,绿色应该是系统默认输入框主题背景,我并没有对主题做任何处理,如果想了解Android M主题相关知识,可以参考之前一篇博客。
当然想实现上面的效果图,我们需要在代码里做一定处理:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputLayout= (TextInputLayout) findViewById(R.id.til);
et= inputLayout.getEditText();
et.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 4) {
inputLayout.setErrorEnabled(true);
inputLayout.setError("姓名长度不能超过4个");
} else {
inputLayout.setErrorEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
把布局文件同时粘贴在这里:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.TextInputLayout
android:id="@+id/til"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<EditText
android:id="@+id/et"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</EditText>
</android.support.design.widget.TextInputLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SnackBar"
android:layout_centerInParent="true"
android:onClick="click"/>
</RelativeLayout>
TextInputLayout 不仅能让EditView的提示语上弹显示在EditView之上,而且还能把错误信息显示在EditView之下。TextInputLayout常用的方法有如下:
Snackbar
个人很喜欢这个控件!
Snackbar提供了一个介于Toast和AlertDialog之间轻量级控件,它可以很方便的提供消息的提示和动作反馈。
Snackbar的使用和Toast很类似,调用代码如下:
public void click(View view){
final Snackbar snackbar = Snackbar.make(et,"测试弹出提示",Snackbar.LENGTH_LONG);
snackbar.show();
snackbar.setAction("取消", new View.OnClickListener() {
@Override
public void onClick(View v) {
snackbar.dismiss();
}
});
}
效果:
后面再来试下FloatingActionButton
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:fabSize="mini"
app:borderWidth="0dp"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
app:backgroundTint="#FF991F1C"
app:rippleColor="#199999"
android:src="@drawable/ic_check_pressed"
android:onClick="clickFab"/>
这是一个浮动按钮。
由于FloatingActionButton是重写ImageView的,所有FloatingActionButton拥有ImageView的一切属性。为了控制FloatingActionButton的大小,背景颜色,阴影的深度等,我们可以通过如下属性来控制这些效果:
效果还是挺赞的!
有问题,或者建议,留言讨论!