首页 > 解决方案 > Android Studio中复选框内的AlertDialog

问题描述

我是 Android Studio 的新手。我想创建一个 AlertDialog,其中包含一个简单的 TextView,它出现在复选框内的每一圈时间(例如 5 分钟),因此如果单击该复选框,AlertDialog 每 5 分钟出现一次。如果未单击,则不会出现任何内容。请帮帮我。

标签: android-studioandroid-dialogandroid-checkboxandroid-timer

解决方案


经过一些实验,我能够创建类似于我认为您想要的东西。这是我创建的小项目,但您可以只获取项目所需的部分代码。

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
{
    TextView input;
    long startTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        final LinearLayout ll = new LinearLayout(this);

        setContentView(ll);

        CheckBox cb = new CheckBox(getApplicationContext());
        cb.setText("Checkbox");
        ll.addView(cb);

        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if (isChecked)
                {
                    startTime = System.currentTimeMillis();
                    timerHandler.postDelayed(timerRunnable, 0);
                }
                else
                {
                    timerHandler.removeCallbacks(timerRunnable);
                }
            }
        });
    }

    public void showDialog()
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Title");
        alert.setMessage("Message");

        input = new TextView (this);
        alert.setView(input);
        input.setText("Text");

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
                // do stuff when Ok is clicked
            }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
                // do stuff when Cancel is clicked
            }
        });
        alert.show();
    }

    Handler timerHandler = new Handler();
    Runnable timerRunnable = new Runnable()
    {
        @Override
        public void run()
        {
            showDialog();
            // Edit the second parameter to whatever time you want in milliseconds
            timerHandler.postDelayed(this, 300_000);
        }
    };

    @Override
    public void onPause()
    {
        super.onPause();
        timerHandler.removeCallbacks(timerRunnable);
    }
}

希望这会有所帮助。


推荐阅读