如何在片段中显示AlertDialog

时间:2015-04-23 06:53:53

标签: android android-fragments alertdialog

我是Java和Android的初学者,请帮忙。我想把Alert Dialog放在一个片段中,但我最终复制了下面类中的大部分代码,所以这两个类包含几乎相同的代码。你能告诉我如何在不复制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;
}

3 个答案:

答案 0 :(得分:0)

试试这段代码,

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");
            }
        });
    }
}

答案 1 :(得分:0)

您可以使用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;
    }

答案 2 :(得分:0)

您可以使用DialogFragment轻松完成此操作。只需阅读文档,他们还提供了如何在您的应用程序中实现的示例。如果你想要一个很好的例子,你可以按照Android DialogFragment Tutorial

HERE是执行该操作的代码

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");
}

快乐的编码欢呼。