我在我的应用程序中有2个编辑文本,1个按钮用于在编辑文本和1个文本视图中添加输入数字以显示结果。如果我的编辑文本选项卡为空或者单击按钮时为null,我想添加一个Toast消息。我搜索并尝试了所有解决方案......似乎没有任何工作。请帮忙!!
这是我添加两个数字的代码。
public class Search {
private FileInputStream fis=null;
private String filename;
public Search(String filename){
this.filename = filename;
File file = new File(filename);
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}
答案 0 :(得分:4)
当用户点击按钮检查时:
if (editText1.getText().toString().trim().length() <= 0) {
Toast.makeText(MainActivity.this, "It's empty", Toast.LENGTH_SHORT).show();
}
修剪它以避免空格。
答案 1 :(得分:1)
要创建并显示Toast,请使用以下代码:
Toast.makeText(this, "Please input number", Toast.LENGTH_LONG).show();
为了正常工作,您应该替换此代码:
if (editText1.equals("")) {
editText1.setError("please input number");
}
if (editText2.equals("")) {
editText2.setError("please input number");
}
用这个:
if (editText1.getText().toString().length() == 0 || editText1.getText().toString().length() == 1) {
Toast.makeText(this, "Please input number", Toast.LENGTH_LONG).show();
}
答案 2 :(得分:1)
您可以尝试使用字符串空,非空或 null 这两项功能。简单回归真或假。它非常适用于所有项目。
if(isEmpty(edittext.getText().toString())){
// your Toast message if string is empty
}
if(isNotEmpty(edittext.getText().toString())){
// your Toast message if string is not empty
}
public static boolean isEmpty(String str) {
if (str == null)
return true;
else if (str.toString().trim().length() == 0)
return true;
return false;
}
public static boolean isNotEmpty(String str) {
if (str == null)
return false;
else if (str.toString().trim().length() == 0)
return false;
return true;
}
答案 3 :(得分:0)
添加到您的点击监听器检查
Toast toast = Toast.makeText(MainActivity.this, "Your Message", Toast.LENGTH_SHORT);
toast.show();
答案 4 :(得分:0)
您的代码将是:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText1 = (EditText)findViewById(R.id.editText1);
final EditText editText2 = (EditText)findViewById(R.id.editText2);
Button button1 = (Button)findViewById(R.id.button1);
final TextView textView1 = (TextView)findViewById(R.id.textView1);
textView1.setText(" ");
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(editText1.getText().toString().trim().length() == 0 || editText2.getText().toString().trim().length() == 0) {
Toast.makeText(this,"Edittext is null",Toast.LENGTH_SHORT).show();
}
else {
double edit1 = Double.valueOf(editText1.getText().toString());
double edit2 = Double.valueOf(editText2.getText().toString());
double text = edit1 + edit2;
textView1.setText(String.valueOf(text));
}
});
}
}