来自片段的Android启动对话框片段

时间:2016-08-18 12:26:50

标签: android android-fragments android-alertdialog

我有一个片段类,它有动作栏图标。就像这样 -

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.action_bar_call, menu);
        super.onCreateOptionsMenu(menu,inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.call:
             //Call Dialog fragment from here
              CallDialogFragment dialog = CallDialogFragment .instantiate(getActivity(), "fragmentTAG");
            dialog.show(getFragmentManager(), "dialog");
                return false;

        }
        return false;
    }

编辑:

public class CallDialogFragment extends DialogFragment {

    public CallDialogFragment () {

    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        View view = getActivity().getLayoutInflater().inflate(R.layout.call_dialog_fragment, new LinearLayout(getActivity()), false);



        // Build dialog
        Dialog builder = new Dialog(getActivity());
        builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
        builder.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        builder.setContentView(view);
        return builder;
    }
}

TheDialogFragment类看起来像这样。我的片段中出现错误,指出不兼容的类型

如何从片段中调用对话框片段

2 个答案:

答案 0 :(得分:1)

调用您的Dialog Fragment,如下所示

@Override
public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.call:
                //Call Dialog fragment from here
                CallDialogFragment dialog = new CallDialogFragment();
                dialog.show(getFragmentManager(), "dialog");

                return true;

        }
        return false;
}

答案 1 :(得分:0)

使用dialogFragment.show(getFragmentManager(), "TAG");其中dialogFragment是DialogFragment类的实例,"TAG"是字符串标记,用于标识片段管理器中的对话框。

根据您的封闭片段是支持库还是标准片段,getFragmentManager()将返回支持或标准片段管理器。

如果您需要获取先前附加的片段实例,请使用findFragmentByTag()方法并转换为对话框片段类,例如:

((MyDialogFragment)getFragmentManager().findFragmentByTag(TAG))...

按先前用于附加/显示对话框片段的标记进行搜索。