我有一个包含5个片段的MainActivity,其中2个片段在右上角的工具栏上有一个帮助图标。我在其他3个片段上隐藏了这个图标。单击帮助图标后,将显示一个警告对话框,其中包含标题,消息和肯定按钮。
这是我的警报对话代码:
public class HelpDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Help");
builder.setMessage("Placeholder");
builder.setPositiveButton("Got It", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {}
});
return builder.create();
}
}
这就是我从MainActivity展示它的方式:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_help:
DialogFragment helpDialog = new HelpDialogFragment();
helpDialog.show(getSupportFragmentManager(), "dialogHelp");
return true;
}
return super.onOptionsItemSelected(item);
}
上面的代码有效,但我想根据所选的片段显示不同的消息,以便如何更改消息?我试着改变头衔
helpDialog.getDialog().setTitle("Some Text");
请注意我想要更改Dialog消息,即主要内容,我只在setTitle()
而不是getDialog()
上获得setMessage()
方法,上面的setTitle
仅用于示例目的,但即使它正在抛出NullPointerException。
正如您在上面的屏幕截图中看到的,“占位符”文本是我在创建AlertDialog时添加的默认文本,但现在如何更改它?
首先在调用HelpDialogFragment类时在包上传递所需的消息
HelpDialogFragment helpDialog = new HelpDialogFragment();
Bundle bundle = new Bundle();
bundle.putString("placeholder", "Custom placeholder");
helpDialog.setArguments(bundle);
helpDialog.show(getSupportFragmentManager(), "dialogHelp");
现在修改HelpDialogFragment类,像这样创建对话框
public class HelpDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Help");
if (getArguments() != null)
builder.setMessage(getArguments().getString("placeholder",""));
builder.setPositiveButton("Got It", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {}
});
return builder.create();
}
}
从阅读您的帖子和评论看起来您需要根据可见的片段设置不同的标题。对话框的创建发生在Activity中,因此您不确定要设置的标题。
问题基本上是识别可见片段并根据它设置消息。
您可以使用这样的参数传递消息。
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(message, "My title");
fragment.setArguments(bundle);
然后在你的片段中,获取数据(例如在onCreate()方法中)
Bundle bundle = this.getArguments();
if (bundle != null) {
String message = bundle.getString(message, defaultValue);
}
如何识别当前可见的片段?您可以按照these答案中的建议执行此操作。获得当前片段后,只需根据它在上面的参数中发送消息。
通过结合上述两个想法,您可以做到这一点。
另一种方法是从片段而不是从Activity启动对话,但这将涉及更多更改,因此上述方法更好。