Android 如何在片段中显示AlertDialog

Android 如何在片段中显示AlertDialog,android,android-fragments,android-alertdialog,Android,Android Fragments,Android Alertdialog,我是Java和Android的初学者,请帮助。我想将警报对话框放在一个片段中,但我最终复制了下面类中的大部分代码,因此两个类包含几乎相同的代码。您能告诉我如何在不复制Fragment类中的大部分代码的情况下分离代码吗 谢谢大家! public class MainActivity extends Activity { private int mInterval = 1000; private Handler mHandler; TextView textView; boolean mStart

我是Java和Android的初学者,请帮助。我想将警报对话框放在一个片段中,但我最终复制了下面类中的大部分代码,因此两个类包含几乎相同的代码。您能告诉我如何在不复制Fragment类中的大部分代码的情况下分离代码吗

谢谢大家!

public class MainActivity extends Activity {

private int mInterval = 1000;
private Handler mHandler;
TextView textView;
boolean mStarted;
final static String simple_Date_Format = "HH:mm:ss SSS";

public void updateStatus() {
    long currentTimeMillis = System.currentTimeMillis();
    Date date = new Date(currentTimeMillis);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(simple_Date_Format);
    String time_now = simpleDateFormat.format(date.getTime());
    textView.setText(time_now);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    long currentTimeMillis = System.currentTimeMillis();

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(currentTimeMillis);

    Date date = new Date(currentTimeMillis);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(simple_Date_Format);
    String time_now = simpleDateFormat.format(date.getTime());
    textView = (TextView) findViewById(R.id.textview);
    textView.setText(time_now);

    mHandler = new Handler();
    startRepeatingTask();

    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    MainActivity.this);

            if (mStarted) {
                alertDialogBuilder.setTitle(R.string.settings);
                alertDialogBuilder.setMessage(R.string.stop_message);

            } else {
                alertDialogBuilder.setTitle(R.string.settings);
                alertDialogBuilder.setMessage(R.string.restart_message);
            }

            alertDialogBuilder.setPositiveButton(R.string.click_me,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!mStarted) {
                                startRepeatingTask();
                            } else {
                                stopRepeatingTask();
                            }

                        }
                    });

            alertDialogBuilder.setCancelable(true);
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
        }
    });
}

Runnable mStatusChecker = new Runnable() {
    @Override
    public void run() {

        updateStatus(); // this function can change value of mInterval.
        mHandler.postDelayed(mStatusChecker, mInterval);

    }
};

void startRepeatingTask() {
    mStatusChecker.run();
    mStarted = true;
}

void stopRepeatingTask() {
    mHandler.removeCallbacks(mStatusChecker);
    mStarted = false;
}
试试这个代码

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends FragmentActivity {

    Button dfragbutton;
    Button alertdfragbutton;
    FragmentManager fm = getSupportFragmentManager();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from activity_main.xml
        setContentView(R.layout.activity_main);

        // Locate the button in activity_main.xml
        dfragbutton = (Button) findViewById(R.id.dfragbutton);
        alertdfragbutton = (Button) findViewById(R.id.alertdfragbutton);

        // Capture button clicks
        dfragbutton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                DFragment dFragment = new DFragment();
                // Show DialogFragment
                dFragment.show(fm, "Dialog Fragment");
            }
        });

        // Capture button clicks
        alertdfragbutton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                AlertDFragment alertdFragment = new AlertDFragment();
                // Show Alert DialogFragment
                alertdFragment.show(fm, "Alert Dialog Fragment");
            }
        });
    }
}

您可以使用
DialogFragment
显示警报
DialogFragment
有一个方法
onCreateDialog
,您可以在其中编写警报弹出逻辑

 @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        mLayoutInflater = LayoutInflater.from(mContext);

        rootView = mLayoutInflater.inflate(R.layout.fragment_info_dialog, null, false);
   alertDialog = builder.create();
        alertDialog.setCancelable(false);
        alertDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);

        return alertDialog;
    }
你可以很容易地用它。只需浏览文档,他们还提供了如何在应用程序中实现的示例。如果你想要一个好的例子,你可以效仿这个例子

下面是执行此操作的代码

public static class MyAlertDialogFragment extends DialogFragment {

public static MyAlertDialogFragment newInstance(int title) {
    MyAlertDialogFragment frag = new MyAlertDialogFragment();
    Bundle args = new Bundle();
    args.putInt("title", title);
    frag.setArguments(args);
    return frag;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    int title = getArguments().getInt("title");

    return new AlertDialog.Builder(getActivity())
            .setIcon(R.drawable.alert_dialog_icon)
            .setTitle(title)
            .setPositiveButton(R.string.alert_dialog_ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        ((FragmentAlertDialog)getActivity()).doPositiveClick();
                    }
                }
            )
            .setNegativeButton(R.string.alert_dialog_cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        ((FragmentAlertDialog)getActivity()).doNegativeClick();
                    }
                }
            )
            .create();
    }
}
创建一个方法并在要显示警报对话框的活动中调用此方法

void showMyDialog() {
    DialogFragment newFragment = MyAlertDialogFragment.newInstance(
        R.string.alert_dialog_two_buttons_title);
    newFragment.show(getFragmentManager(), "dialog");
}

愉快的编码干杯。

哦,对不起,我正在扩展碎片活动。您能告诉我更多信息吗?是否仅在片段中显示AlertDialog?是否通过避免相同代码的冗余,在两个片段中显示对话框?