AlertDialog无法在片段中工作

时间:2017-04-07 15:07:03

标签: android android-fragments alertdialog timepicker

你好我正在做一个按下按钮的应用程序,并弹出一个带有TimePicker的AlertDialog窗口。但它位于片段中,因此AppCompatActivity不会这样做。

碎片本身:

public class time_change extends Fragment implements  TimePickerFragment.TimeDialogListener {
private static final String DIALOG_TIME = "MainActivity.TimeDialog";

private View v;
private Button timePickerAlertDialog;
private ImageButton back;

@Override
@Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.pamokos, container, false);

    timePickerAlertDialog = (Button) v.findViewById(R.id.alert_dialog_time_picker);

    timePickerAlertDialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            TimePickerFragment dialog = TimePickerFragment.newInstance();
            dialog.show(getActivity().getFragmentManager(), "TimePickerFragment");
        }
    });

    back = (ImageButton) v.findViewById(R.id.back_btn1);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Pamokos fr = new Pamokos();
            time_change fr2 = new time_change();
            android.app.FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.activity_frag, fr);
            fragmentTransaction.remove(fr2);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
        }

    });
    return v;
}

@Override
public void onFinishDialog(String time) {
    Toast.makeText(getActivity(), "Selected Time : " + time, Toast.LENGTH_SHORT).show();
}
}

但它在

显示错误
dialog.show(getActivity().getFragmentManager(), "TimePickerFragment");

说“无法解析方法”show(android.app.FragmentManager,java.lang.String)'“

完整代码来自本教程https://www.androidtutorialpoint.com/basics/android-alert-dialog-tutorial-working-time-picker-date-picker-list-dialogs/

我很失落。

2 个答案:

答案 0 :(得分:2)

替换

TimePickerFragment dialog = TimePickerFragment.newInstance();
dialog.show(getActivity().getFragmentManager(), "TimePickerFragment");

用这个

 FragmentManager fm = getActivity().getSupportFragmentManager();
 TimePickerFragment dialog = new TimePickerFragment ();
 dialog.show(fm, "TimePickerFragment");

答案 1 :(得分:1)

添加 下面 在DialogFragment类中导入

import android.support.v4.app.DialogFragment;

替换

dialog.show(getActivity().getFragmentManager(), "TimePickerFragment");

dialog.show(getSupportFragmentManager(), "TimePickerFragment");