我正在扩展DialogFragment,但我无法检索通过DialogFragment UI输入的文本。由于某种原因,我得到一个空字符串(“”)。
也许: 1)。它并没有通过获取正确的视图 查看v = inflater.inflate(R.layout.add_dialog,null); 2)。它没有抓住正确的EditText 3)。我需要通过DialogInterface对象使用一些东西 通过param传递
谢谢你, 彼得
代码.....
public class AddDialog extends DialogFragment {
EditText editText;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final foodhouseDatabaseAdapter myDBAdapter;
myDBAdapter = new foodhouseDatabaseAdapter(this.getActivity());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setMessage("Please enter the item to be added");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// 'Close dialog box' ? .dismiss() ???
}
});
builder.setNegativeButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
View v = inflater.inflate(R.layout.add_dialog, null);
/**
* this line is setting 'editText' to an empty string
*/
editText = (EditText) v.findViewById(R.id.user_entered_item_name);
String x = editText.getText().toString();
if (!x.isEmpty()) {
// Capitalize first letter of user entered string
String item = capitalizeFirstLetter(x);
long ID = myDBAdapter.insertData(1, item);
if (ID < 0) {
Message.message(getActivity(), "Item was not added");
} else {
Message.message(getActivity(), item + " added");
editText.setText("");
}
} else {
Message.message(getActivity(), "We did not see anything to insert");
}
}
});
builder.setView(inflater.inflate(R.layout.add_dialog, null));
return builder.create();
}
/** http://stackoverflow.com/questions/5725892/
* how-to-capitalize-the-first-letter-of-word-in-a-string-using-java */
public String capitalizeFirstLetter(String original){
if(original.length() == 0)
return original;
return original.substring(0, 1).toUpperCase(Locale.US) + original.substring(1);
}
}
答案 0 :(得分:1)
你得到了错误的方式。使用getSystemService
示例:
LayoutInflater inflater = (LayoutInflater) getActivity.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
答案 1 :(得分:0)
在您的问题代码中,从您的onClick侦听器中删除View v = inflater.inflate(R.layout.add_dialog, null); editText = (EditText) v.findViewById(R.id.user_entered_item_name);
,并将其替换为editText = (EditText) getDialog().findViewById(R.id.user_entered_item_name);
。
问题是你是两次膨胀而没有得到第一个你膨胀的编辑文本并用setView放入Dialog。