我正在寻找一种将数据从一个活动传递到对话框的方法。我尝试调用showDialog(int);
,但是我没有看到任何将数据传递给对话框的方法。
为了显示确认信息,我需要将一个字符串传递给对话框 :)
谢谢
我正在寻找一种将数据从一个活动传递到对话框的方法。我尝试调用showDialog(int);
,但是我没有看到任何将数据传递给对话框的方法。
为了显示确认信息,我需要将一个字符串传递给对话框 :)
谢谢
如果你的目标是 Android 2.2 (API 级别为 8 或更高),你可以使用
public final boolean showDialog (int id, Bundle args)
并且将参数传递到Bundle
中。请参阅文档。
如果您希望支持旧版Android,您应该将参数保存在Activity
类成员中,然后从您的onPrepareDialog
函数中访问它们。请注意,onCreateDialog
不能满足您的需求,因为它仅在对话框创建时调用一次。
class MyActivity {
private static int MY_DLG = 1;
private String m_dlgMsg;
private showMyDialog(String msg){
m_dlgMsg = msg;
showDialog(MY_DLG);
}
private doSomething() {
...
showMyDlg("some text");
}
protected void onCreateDialog(int id){
if(id == MY_DLG){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
....
return builder.create();
}
return super.onCreateDialog(id);
}
@Override
protected void onPrepareDialog (int id, Dialog dialog){
if(id == MY_DLG){
AlertDialog adlg = (AlertDialog)dialog;
adlg.setMessage(m_dlgMsg);
} else {
super.onPrepareDialog(id, dialog);
}
}
}
setArguments
方法。String myString = "How to do it"
DialogFragment newFragment = new AddUserDialog();
Bundle args = new Bundle();
args.putString("number", myString); //The first parameter is the key that will be used to retrieve the value, which is the second parameter.
newFragment.setArguments(args);
newFragment.show(getSupportFragmentManager(), "add_a_member");
//`enter code here`I used shared preferences and it worked.
**in your activity:**
//your field: public static final String GAME_PREFERENCES = null;
String template = selectedItem.getProduct().getName();
String num = selectedItem.getNumber();
String id = selectedItem.getId();
String location = selectedItem.getLocationName();
SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES,
MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString("template", template);
prefEditor.putString("num", num);
prefEditor.putString("id", id);
prefEditor.putString("location", location);
prefEditor.commit();
**in your dialog class:**
//In my case I needed to add activity because how i created dialog:
public MyDialog(Context context, int theme) {
super(context, theme);
init(context);
}
private void init(Context context) {
setContentView(R.layout.dialog);
this.context = context;
final Activity activity = (Activity) context;
// If you dont call activity you can try context.getpreferences(......)
SharedPreferences prefs = ((Activity) context)
.getPreferences(Context.MODE_PRIVATE);
String template = prefs.getString("template", "");
String num = prefs.getString("num", "");
String id = prefs.getString("id", "");
String location = prefs.getString("location", "");
}`enter code here`