我选择使用可点击的类别来提示接受用户输入的对话框,而不是使用 EditTexts。这个可重用的 Dialog 类存储在 AllMethods.class 中。最初的理论是我传递了一堆文本(用于描述、标题等)和一个目标 TextView(用于用户在对话框中输入的 setText)。但是,在执行时,尝试执行 TextView.setText(str) 代码行时出现空指针异常。
所以,我的问题是:如何在用户单击“确定”按钮后成功更改 textView 或返回字符串?
另请注意,TextView 已被声明和实例化。我假设空指针是因为它在远程类中。这是代码:
import android.app.Activity;
import android.app.Dialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class AllMethods {
//fieldRequest is a reusable prompt to get a user's input for a field without taking up so much space
/* Legend of inputs:
* requestingActivity=the activity which is prompting the popup
* dialogMessage = the description of the editText being requested
* dialogTitle = the title to be displayed on the dialogbox
* editTextHint = the Hint attribute that will give the user an example of the expected input
* inputType = numeric, text, phone number, etc
*/
public static void fieldRequest(Activity activity, String dialogMessage, String dialogTitle, final TextView outputText, int inputType, String optionalFieldSuffix){
final Dialog dialog= new Dialog(activity);
dialog.setContentView(R.layout.dialog_layout);
dialog.setTitle(dialogTitle);
//If the message/description exists, put it in
if(dialogMessage!=null||dialogMessage!=""){TextView description = (TextView) dialog.findViewById(R.id.dialog_description);
description.setText(dialogMessage);
}
//Identify the editText, set the input type appropriately and fill in the hint if applicable
final EditText inputField = (EditText) dialog.findViewById(R.id.dialog_inputbox);
if(Integer.toString(inputType)!=null){inputField.setInputType(inputType);}
if(optionalFieldSuffix!=null){TextView suffix = (TextView) dialog.findViewById(R.id.dialog_optionalFieldSuffix);
suffix.setText(optionalFieldSuffix);}
ImageButton dialogCancel = (ImageButton) dialog.findViewById(R.id.dialog_cancel);
ImageButton dialogDone = (ImageButton) dialog.findViewById(R.id.dialog_done);
dialogCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialogDone.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
outputText.setText(inputField.getText().toString());
dialog.dismiss();
}
});
dialog.show();
}
}