我在自定义对话框中从EditText对象获取输入时未能成功。
public class SetCityDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
final View view = factory.inflate(R.layout.city_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.city_dialog, null))
// Add action buttons
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
//This is the input I can't get text from
EditText inputTemp = (EditText) view.findViewById(R.id.search_input_text);
//query is of the String type
query = inputTemp.getText().toString();
newQuery();
getJSON newData = new getJSON();
newData.execute("Test");
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
SetCityDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
我没有任何异常,但变量查询被设置为空字符串。 任何帮助都会很棒。
答案 0 :(得分:14)
我试图做同样的事情,我得到同样的错误。我不知道为什么。我过去已经使用过AlertDialog.Builder而且没有遇到麻烦。但在您的情况下,请更改此代码:
public void onClick(DialogInterface dialog,
int id) {
//This is the input I can't get text from
EditText inputTemp = (EditText) view.findViewById(R.id.search_input_text);
//query is of the String type
query = inputTemp.getText().toString();
newQuery();
getJSON newData = new getJSON();
newData.execute("Test");
}
通过这个:
public void onClick(DialogInterface dialog,
int id) {
Dialog f = (Dialog) dialog;
//This is the input I can't get text from
EditText inputTemp = (EditText) f.findViewById(R.id.search_input_text);
query = inputTemp.getText().toString();
...
}
这个解决方案对我有用,对你来说似乎也是一样。 找到stackoverflow
答案 1 :(得分:4)
请改用:
View myLayout = nflater.inflate(R.layout.city_dialog, null);
EditText myEditText = (EditText) myLayout.findViewById(R.id.myEditText);
String valueOfEditText = myEditText.getText().toString();
答案 2 :(得分:0)
无需编写那么多代码。只是改变
builder.setView(inflater.inflate(R.layout.city_dialog, null))
到
builder.setView(view)
使用** view.findView .....
访问EditText的文本 EditText inputTemp = (EditText) view.findViewById(R.id.search_input_text);
String xyz = inputTemp.getText().toString();
答案 3 :(得分:0)
This is worked for me:
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
Dialog inDialog = (Dialog) dialog;
EditText emailAddress = (EditText) inDialog.findViewById(R.id.emailAddress);
email = emailAddress.getText().toString();
if(email.length() == 0) {
objPublicDelegate.showToast("Please fill Email Address.");
}else{
objLoadingDialog.show("Please wait...");
// Call a network thread Async task
mNetworkMaster.runForgetAsync(email);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});