我想创建一个对输入长度有限制的edittext。当edittext长度大于5时,它应显示错误Toast消息。该应用程序编译但它在模拟器中崩溃并且无法打开。我的代码如下,任何帮助都将不胜感激。
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="@+id/etext1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="B1"
android:id="@+id/one"
android:text="1"
android:layout_below="@+id/etext1"
android:gravity="center"
/>
Java代码如下所示:
public class MainActivity extends ActionBarActivity {
EditText tx=(EditText)findViewById(R.id.etext1);
String a;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void B1(View v) {
if (tx.getText().toString().length()>5)
{
LayoutInflater inflater = getLayoutInflater();
View erro = inflater.inflate(R.layout.error, (ViewGroup) findViewById(R.id.idoferror));
Toast dis = Toast.makeText(this, "er", Toast.LENGTH_LONG);
dis.setGravity(Gravity.CENTER | Gravity.RIGHT, 0, 0);
dis.setView(erro);
dis.show();
}
else {
a=tx.getText().toString();
a=a+1;
tx.setText(a);
}
}
}
答案 0 :(得分:1)
移动这个
EditText tx=(EditText)findViewById(R.id.etext1);
onCreate()
中的一行并设置android:maxLength="5"
EditText tx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tx=(EditText)findViewById(R.id.etext1);
}
答案 1 :(得分:0)
要在达到限制字符时显示Toast
。您需要将TextWatcher
添加到EditText
每次向EditText
输入文字后,请检查EditText
的长度,然后再次显示Toast
和setText()
,如果需要,请EditText
< / p>
final int MAX_CHARACTERS = 5;
...
yourEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
if (yourEditText.toString().length() > MAX_CHARACTERS) {
yourEditText.setText(yourEditText.getText().toString().substring(0, MAX_CHARACTERS));
Toast.makeText(getActivity(), "Maximum number of characters reached.", Toast.LENGTH_SHORT).show();
}
}
});
===
如果您只想限制文本长度,请不要显示Toast
。你可以使用
yourEditText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(MAX_CHARACTERS)});
或XML
android:maxLength="5"
希望这个帮助