使用getFragmentManager Android时出现冲突

时间:2014-06-17 22:11:31

标签: android alertdialog android-support-library android-dialogfragment

MainActivity定义为sdk从11到19,有2个库,google-play-services和appcompat_v7,最后一个有android-support-v4.jar,我的项目没有,我删除了它的一个因为SHA冲突一切顺利,直到我决定添加片段对话框。首先,我创建了一个带有下面定义的类的java文件

package com.mypack;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

public class MyAlertDialogWIndow extends DialogFragment{
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.hello_world)
           .setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
               @Override
            public void onClick(DialogInterface dialog, int which) {
               // The 'which' argument contains the index position
               // of the selected item
           }
    });
    return builder.create();
  }
}

在主要活动中,按下时按钮会显示对话框,

public void launch_service_colors(View view){
    //do some other stuff
      FragmentManager fm = getFragmentManager();
      MyAlertDialogWIndow alert = new MyAlertDialogWIndow();
      alert.show(fm, "Alert_Dialog");
}

和Eclipse编辑器抱怨getFragmentManager(),它说类型不匹配:无法从android.app.FragmentManager转换为android.support.v4.app.FragmentManager ,好吧所以我试过通过getSupportFragmentManager()更改它,编辑器现在说方法getSupportFragmentManager()未定义类型MainActivity 。我不知道还能做什么: - (

1 个答案:

答案 0 :(得分:0)

从支持库中MainActivity延长FragmentActivity

import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {

   ...

   FragmentManager fm = getSupportFragmentManager();

   ...
}

如果您没有使用支持库,请不要使用库提供的DialogFragment,请使用android.app.DialogFragment

import android.app.DialogFragment;

public class MyAlertDialogWIndow extends DialogFragment {
   ...
}