我有一个应用程序,可以让用户输入文本并将其导出到 txt 文件。当用户按下保存按钮时,会出现一个对话框,询问用户如何命名文件。用户输入一个名称,该名称被视为字符串值,然后将其与“.txt”连接起来作为最终文件名。问题是程序立即保存文件而不等待用户输入名称,因此它将使用字符串的先前值,即使它为空。当它为空时,文件名将为“null.txt”。下次用户尝试保存文件时,应用程序将立即保存文件并使用之前在第一次尝试中输入的值,如此继续。
保存按钮:
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openDialog(); //Calls for the dialog pop-up
exportText = resultText.getText().toString().trim(); //.trim() removes space before and after text
if (!exportText.isEmpty()) {
saveToTxtFile(exportText);
} else {
Toast.makeText(SpeechToText.this, "Input field empty...", Toast.LENGTH_SHORT).show();
}
}
});
保存方法:
private void saveToTxtFile(String mText) {
try {
File path = Environment.getExternalStorageDirectory(); //path to storage
File dir = new File(path + "/My App/Text Files/"); //create folders
dir.mkdirs();
String fileName = inputName + ".txt";
File file = new File(dir, fileName);
//FileWriter class is used to store characters in file
FileWriter fw = new FileWriter(file.getAbsolutePath());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(mText);
bw.close();
Toast.makeText(SpeechToText.this, "Saved successfully...", Toast.LENGTH_SHORT).show();
} catch(Exception e) {
//if anything goes wrong
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
对话框弹出方法:
public void openDialog() {
View view = (LayoutInflater.from(SpeechToText.this)).inflate(R.layout.user_input, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(SpeechToText.this);
alertBuilder.setView(view);
final EditText userInput = view.findViewById(R.id.userInput);
alertBuilder.setCancelable(true).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
inputName = String.valueOf(userInput.getText());
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
}
最佳答案
您正在调用 saveToTxtFile()
,然后用户才能在对话框提示中输入文件名。
只需在 inputName = String.valueOf(userInput.getText());
之后在对话框 onClick
监听器中调用它,并进行 null 检查。另外,如果你改变你的文件保存方式会更好
saveToTxtFile(String mText)
到
saveToTxtFile(String mText, String filename)
这样您就可以确定传递给此方法的文件名是什么。
像这样
alertBuilder.setCancelable(true).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
inputName = String.valueOf(userInput.getText());
if(inputName != "" && inputName != null)
saveToTxtFile(exportText,inputName);
else
//Toast an error here
}
});
还在您的 saveBtn
点击监听器调用 openDialog()
中,您在 if () 内调用
主体。 saveToTxtFile(exportText);
!exportText.isEmpty())
像这样:
exportText = resultText.getText().toString().trim(); //.trim() removes space before and after text
if (!exportText.isEmpty()) {
openDialog();
} else {
Toast.makeText(SpeechToText.this, "Input field empty...", Toast.LENGTH_SHORT).show();
}
这样,如果文件内容不为空,它只会询问文件名。
关于java - 暂停代码,直到用户在对话框提示中输入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57005246/