如何让对话框在片段中工作?

时间:2019-03-23 04:53:46

标签: java android

我正在尝试在片段中使用浮动操作按钮来弹出一个对话框来创建新帖子。我遇到的问题是我在以下代码行中收到错误:

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_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>

该应用程序将无法运行,因为我收到错误消息:

error: incompatible types: ForumFragment cannot be converted to Context

任何建议将不胜感激!

2 个答案:

答案 0 :(得分:0)

像这样更新您的 iniPopup()方法:

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;
}

如有任何查询,请通知我。

答案 1 :(得分:0)

您应该使用适当的上下文来初始化对话框,它可以是Fragment所在的上下文,也可以是保存Fragment的活动。因此,替换此行:

popAddPost = new Dialog(this);

由此:

popAddPost = new Dialog(getActivity());