我正在擴展DialogFragment,並且無法檢索通過DialogFragment UI輸入的文本。由於某種原因,我得到一個空字符串(「」)。我無法從DialogFragment中的EditText對象中獲取文本(獲取空字符串,即「」)
也許: 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);
}
}
Thx @Rod_Algonquin,但是在獲得了inflater的建議後,editText仍然被設置爲一個空字符串(「」)。你認爲在這個語句中使用'null'而不是ViewGroup:View v = inflater.inflate(R.layout.add_dialog,null);可能會導致這? –
@PeterBaldwin而不是做這個builder.setView(inflater.inflate(R.layout.add_dialog,null));只需像這樣設置視圖builder.setView(v);所以你可以得到你的edditext –
非常感謝。我在這個問題上花了太多時間。如果沒有太多的麻煩,你會不會很快告訴我爲什麼調用builder.setView()允許我抓取文本,而另一種方式卻不行? –