我正在使用 material-dialogs 库
https://github.com/afollestad/material-dialogs
我的问题是我无法使用 fragment 中的库
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
layout=inflater.inflate(R.layout.fragment_option, null);
new MaterialDialog.Builder(this) //the problem is this line
.title("test")
.content("test")
.show();
return layout;
}
下面的方法我都试过了,都失败了
new MaterialDialog.Builder(getActivity())
new MaterialDialog.Builder(this.getActivity())
new MaterialDialog.Builder(MainActivity.this) //MainActivity is the parent activity
感谢您提供的任何帮助
最佳答案
您无法在 Fragment
的 onCreateView()
方法中获取 context
因为 fragment 未添加到 Activity
.
唯一的方法是在onAttach(Activity activity)
(或者Fragment
的lifecicle后面的方法)的方法中获取
。 Context
> fragment
所以你可以这样显示对话框:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Context ctx=this.getActivity();
new MaterialDialog.Builder(ctx)
.title("test")
.content("test")
.show();
}
UPD_0:
确保您在自己的应用中使用 23.0.1 版的 Google 库(AppCompat、支持库等)。 ( link )
UPD_1:
由于 onAttach(Activity activity)
已弃用,请使用 onAttach(Context context)
关于android - 在 fragment 中使用 Material 对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32798224/