android-studio - Android Studio中复选框内的AlertDialog
问题描述
我是 Android Studio 的新手。我想创建一个 AlertDialog,其中包含一个简单的 TextView,它出现在复选框内的每一圈时间(例如 5 分钟),因此如果单击该复选框,AlertDialog 每 5 分钟出现一次。如果未单击,则不会出现任何内容。请帮帮我。
解决方案
经过一些实验,我能够创建类似于我认为您想要的东西。这是我创建的小项目,但您可以只获取项目所需的部分代码。
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);
}
}
希望这会有所帮助。
推荐阅读
- python - 如何在 Python 中设置双重嵌套列表的元素?
- python - 程序在 while 循环期间忽略 if 语句
- python - 为什么我的烧瓶应用程序没有连接到云 Firestore?我写了这段代码
- reactjs - Typescript React无法在对象内找到属性
- javascript - 如何检测 iFrame 的卸载事件
- c# - 根据另一个组合框2填充组合框1
- r - 按类别数据框分组和子集
- c++ - 任何人都知道如何初始化一个空数组
- azure - Unable to update Azure Network Security Group using az cli
- javascript - 代码不适用于更大范围的数字