【问题标题】:Using getResources().getString inside a DialogFragment - crash在 DialogFragment 中使用 getResources().getString - 崩溃
【发布时间】:2015-05-26 17:39:58
【问题描述】:
我在启动应用程序时显示了对话框(该类从 MainActivity 使用)。我想使用 strings.xml 中的字符串,但是当我使用 getResources().getString(R.string.stringname) 时,它会使应用程序崩溃,并给出它未附加到活动的错误。我该如何解决?
【问题讨论】:
标签:
android
string
android-dialogfragment
【解决方案1】:
你应该使用 ApplicaitonContext,简单如下:
MiyaApplication.getApplication().getApplicationContext().getResources().getString(R.string.loading);
【解决方案2】:
如果你有错误说"dialog is not attached to the activity",我认为问题不在于字符串资源。
您很可能正在显示来自后台服务的对话框。您不能简单地显示带有应用程序上下文实例的普通对话框。您需要一个活动窗口来保存您的对话框。
但是,如果您确实需要从后台服务显示对话框(您的应用程序没有活动),您应该使用 对话框样式的活动。
将此属性放在 AndroidManifest.xml 的活动部分中
<activity android:theme="@android:style/Theme.Dialog">