我正在尝试使用seterror方法验证edittext。我正在使用焦点更改的侦听器来检查edittext的长度是否为零。但是当我尝试键入所需的edittext时,我无法输入并且文本正在输入第二个。请帮助!!
代码:
package com.example.usernamevalidation;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText txtusername,txtpassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtusername=(EditText) findViewById(R.id.txtusername);
txtpassword=(EditText) findViewById(R.id.txtpassword);
txtusername.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
if(txtusername.getText().toString().length()==0)
{
txtusername.requestFocus();
txtusername.setError("Username cannot be left blank");
}
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<EditText
android:layout_width="300px"
android:layout_height="wrap_content"
android:id="@+id/txtusername"
/>
<EditText
android:layout_width="300px"
android:layout_height="wrap_content"
android:id="@+id/txtpassword"
/>
</LinearLayout>
答案 0 :(得分:0)
Remove this line : txtusername.requestFocus();
答案 1 :(得分:0)
使用TextWatcher
并在onTextChanged()
检查您想要的任何内容。
答案 2 :(得分:0)
很简单,你创建了更多代码更复杂让我们试试这段代码使用TextUtils TextUtils.isEmpty
- 如果字符串为null或0-length,则返回true。
EditText txtusername = (EditText) findViewById(R.id.txtusername);
EditText txtpassword = (EditText) findViewById(R.id.txtpassword);
if(TextUtils.isEmpty(txtusername.getText().toString())){
txtusername.setError("Username cannot be left blank");
txtusername.requestFocus();
}
if(TextUtils.isEmpty(txtpassword.getText().toString())){
txtpassword.setError("password cannot be left blank");
txtpassword.requestFocus();
}
//do logging process