单击Edittext后,我需要显示错误标签。 例如,在活动开始时,不应显示错误标签。 当然,聚焦的edittext是edtFirstName,如果我单击edtLastName并将edtFirstName留空,它应该显示错误消息。与edtLastName相同。我的问题是在最开始,edtLastName的错误标签已经显示其错误标签“不能为空”。它甚至在活动开始时调用onFocusChange,因为焦点位于edtFirstname。我该怎么办呢?我想做Android上的谷歌添加帐户。
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.content_signup, container, false);
edtFirstName = (EditText) view.findViewById(R.id.edtFirstName);
edtLastName = (EditText) view.findViewById(R.id.edtLastName);
tilFName = (TextInputLayout) view.findViewById(R.id.tilFName);
tilLName = (TextInputLayout) view.findViewById(R.id.tilLName);
edtFirstName.setOnFocusChangeListener(this);
edtLastName.setOnFocusChangeListener(this);
然后
@Override
public void onFocusChange(View v, boolean hasFocus) {
boolean flag = false;
// First Name
if (!edtFirstName.hasFocus())
{
if (edtFirstName.getText().toString().isEmpty())
{
tilFName.setError("Must not be empty.");
}
else
{
tilFName.setError(null);
}
}
if (!edtLastName.hasFocus()) // this is triggered at the start of the activity.
{
if (edtLastName.getText().toString().isEmpty())
{
tilLName.setError("Must not be empty.");
}
else
{
tilLName.setError(null);
}
}
是否有合适的LostFocus代码?
答案 0 :(得分:0)
将其添加到Activity
的父XML
布局容器中:
android:focusable="true"
android:focusableInTouchMode="true"
即如果您使用的是RelativeLayout
:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
tools:context="com.example.activities.SampleActivity">
答案 1 :(得分:0)
试试这个
{{1}}
答案 2 :(得分:0)
经过数小时的尝试后,我能够解决自己的问题
edtFirstName.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
edtFirstName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!edtFirstName.hasFocus()) {
if (edtFirstName.getText().toString().isEmpty()) {
tilFName.setError("Must not be empty.");
} else {
tilFName.setError(null);
}
}
}
});
return false;
}
});
edtLastName.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
edtLastName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!edtLastName.hasFocus()) {
if (edtLastName.getText().toString().isEmpty()) {
tilLName.setError("Must not be empty.");
} else {
tilLName.setError(null);
}
}
}
});
return false;
}
});
也许我必须缩短代码,因为我还有其他的edittexts在等待。大声笑。感谢你的帮助!