在Andriod 中与用户交互的时候,不免会带来一些提示。为了更好的用户体验,我们又不能老是给用户弹出Dialog,反正个人觉得Dialog是一个非常不好的东西,老是我在弄着弄着就弹出来了,用户交互很是不好。后面突然发现EditText 有一个SetError 方法,看起来也还不错,也解决了一些输入的不少问题,如果你没有用过这个方法,你可以去试试喔,肯定比弹出一个Dialog要好很多。
但是,他也是存在问题的,这个问题,到现在我也没能很好的解决,只是有一个替代方案。
好了,先说问题:
在EditText和软键盘同时出现的时候,EditText中setError("Message")弹出的提示,会因为软键盘的出现和隐藏,出现一系列的bug,在stackoverflow上面有好多类似的问题,但是都没有一个很好的解决方案。如果你有什么好的解决办法,请告诉我一下:lovecluo@nightweaver.org
我使用的解决方案:
在EditText上面添加一个1dp高的TextView,检测TextView的位置变化,然后更新EditText的setError方法.
不多说,上代码:
// activity_main.xml
<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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" >
<EditText android:id="@+id/et" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" />
<TextView android:id="@+id/flag" android:layout_width="1dp" android:layout_height="1dp" android:layout_above="@+id/tv" />
</RelativeLayout> |
// MainActivity.java
package org.nightweaver.edittexterror;
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.EditText; import android.widget.TextView;
public class MainActivity extends Activity {
private EditText et;// 文本输入 private TextView v;// 检测位置 private int x;
// 定义一个Handler,用来更新UI Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); et.setError(et.getError()); }
};
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); v = (TextView) this.findViewById(R.id.flag); et = (EditText) this.findViewById(R.id.et); et.setError("Error"); int[] location = new int[2]; v.getLocationOnScreen(location); x = location[1]; initListener(); }
private void initListener() { new Thread(new Runnable() {
@Override public void run() { while (true) { int[] location = new int[2]; v.getLocationOnScreen(location); if (x != location[1]) { x = location[1]; } else { handler.sendEmptyMessage(1); } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } } |
运行效果如下图所示:
如果你的模拟器没有软键盘,你可以将下面红色框中的勾去掉,这样就有软键盘了。如下图所示