Java 如何使对话框在片段中工作?
我试图在一个片段中使用一个浮动操作按钮来打开一个对话框来创建一个新的帖子。我遇到的问题是,我在这行代码中遇到了一个错误:Java 如何使对话框在片段中工作?,java,android,Java,Android,我试图在一个片段中使用一个浮动操作按钮来打开一个对话框来创建一个新的帖子。我遇到的问题是,我在这行代码中遇到了一个错误: popAddPost = new Dialog(this); 错误说明: Dialog (android.content.context) in Dialog cannot be applied to (com.comhar.firebaseapp.Fragments.ForumFragment) 我尝试过使用一些在网上找到的解决方案,但没有一个奏效 ForumFragm
popAddPost = new Dialog(this);
错误说明:
Dialog (android.content.context) in Dialog cannot be applied to (com.comhar.firebaseapp.Fragments.ForumFragment)
我尝试过使用一些在网上找到的解决方案,但没有一个奏效
ForumFragment.java
public class ForumFragment extends Fragment {
Dialog popAddPost;
public ForumFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_forum, container, false);
iniPopup();
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
popAddPost.show();
}
});
return view;
}
private void iniPopup() {
popAddPost = new Dialog(this);
popAddPost.setContentView(R.layout.popup_add_post);
popAddPost.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popAddPost.getWindow().setLayout(Toolbar.LayoutParams.MATCH_PARENT,Toolbar.LayoutParams.WRAP_CONTENT);
popAddPost.getWindow().getAttributes().gravity = Gravity.TOP;
}
}
fragment\u forum.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.ForumFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="forum" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="20dp"
android:src="@drawable/nep_post" />
</FrameLayout>
当我收到错误时,应用程序将不会运行:
错误:不兼容的类型:ForumFragment无法转换为上下文
任何建议都将不胜感激 像这样更新您的IniPoop()方法:
private void iniPopup() {
popAddPost = new Dialog(getActivity());
popAddPost.setContentView(R.layout.activity_login);
popAddPost.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popAddPost.getWindow().setLayout(Toolbar.LayoutParams.MATCH_PARENT, Toolbar.LayoutParams.WRAP_CONTENT);
popAddPost.getWindow().getAttributes().gravity = Gravity.TOP;
}
如果有任何查询,请告诉我。您应该使用适当的上下文初始化对话框,它可以是片段所在的上下文,也可以是保存片段的活动。因此,替换这一行:
popAddPost = new Dialog(this);
据此:
popAddPost = new Dialog(getActivity());
你好@cian404,你试过我下面的答案了吗?它帮助你解决了你的问题吗?如果是这样,请考虑通过点击左边的箭头来标记我的答案。因此,其他人也可以从解决方案中受益。