如何在活动中显示自定义的DialogFragment

时间:2016-01-07 11:27:27

标签: java android dialogfragment

我正在尝试构建AlertDialog并希望在主要活动开始时显示它。但是当活动开始时,会出现错误:

android.util.AndroidRuntimeException: Window feature must be requested before adding content

我首先要做的是创建AlertFragment

public class AlertFragment extends DialogFragment{

    public static AlertFragment newInstance(){
        return new AlertFragment();
    }

    public AlertFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle SavedInstanceState){

        super.onCreateView(inflater, container, SavedInstanceState);

        return inflater.inflate(R.layout.alert_dialog, container, false);
    }

    @Override
    public Dialog onCreateDialog(Bundle SaveInstanceState){

        return new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Dialog)).setMessage("Alert Dialog").setPositiveButton("Set", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getContext(), "Positive", Toast.LENGTH_SHORT).show();
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getContext(), "Negative", Toast.LENGTH_SHORT).show();
            }
        }).create();
    }
}

以下是主要活动:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AlertFragment AF = AlertFragment.newInstance();
        AF.show(getSupportFragmentManager(), "Dialog");
    }
}

有人能告诉我问题在哪里吗?

2 个答案:

答案 0 :(得分:0)

在AlertFragment中删除oncreateview并运行

public class AlertFragment extends DialogFragment{

public static AlertFragment newInstance(){
    return new AlertFragment(); }

public AlertFragment(){}



@Override 
public Dialog onCreateDialog(Bundle SaveInstanceState){

    return new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Dialog)).setMessage("Alert Dialog").setPositiveButton("Set", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getContext(), "Positive", Toast.LENGTH_SHORT).show();
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getContext(), "Negative", Toast.LENGTH_SHORT).show();
        }
    }).create(); 
} 

}

答案 1 :(得分:0)

只需在代码中使用show代替create,如下所示:

{{1}}