我希望AlertDialog的消息“1”出现在屏幕上,3秒后消失,然后我想要另一个警告消息,消息“2”出现在屏幕上,3秒后消失,依此类推,直到5。我有以下代码:
[Activity(Label = "TestAlertDialogBuilder", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
for (int i=0; i <=5 ; i++)
{
//making the program stop so I can see the alert showing and dissappearing
System.Threading.Thread.Sleep(3000);
ShowAlert(i);
}
}
Dialog dialog;
public void ShowAlert(int i)
{
if (dialog != null)
{
dialog.Cancel();
}
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.SetMessage(i.ToString());
dialog = alertDialog.Create();
dialog.Show();
}
}
但是在程序执行一段时间之后,我只得到一个带有消息“5”的AlertDialog,就是这样。如果有人认为我的问题的另一个标题更合适,他可以改变它。
答案 0 :(得分:1)
转换Mohamed Mohaideen AH对C#语言的回答。
public class MyRunnable : Java.Lang.Object, Java.Lang.IRunnable
{
private MainActivity mainActivity;
public MyRunnable(MainActivity mainActivity)
{
this.mainActivity = mainActivity;
}
public void Run()
{
for (int i = 0; i <= 5; i++)
{
try
{
Java.Lang.Thread.Sleep(3000);
}
catch (Java.Lang.Exception e)
{
e.PrintStackTrace();
}
mainActivity.RunOnUiThread(() =>
{
mainActivity.ShowAlert(i);
});
}
}
}
[Activity(Label = "App5", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
MyRunnable myRunnable = new MyRunnable(this);
Java.Lang.Thread thread = new Java.Lang.Thread(myRunnable);
thread.Start();
}
Dialog dialog;
public void ShowAlert(int i)
{
if (dialog != null)
{
dialog.Cancel();
}
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.SetMessage("AlertDialog: " + i);
dialog = alertDialog.Create();
dialog.Show();
}
}
答案 1 :(得分:0)
由于阻止UI主线程直到执行循环而发生问题。因此,为对话框创建单独的线程&amp;在UI中显示它。
试试这个
Thread thread = new Thread(new Runnable() {
int i = 0;
@Override
public void run() {
for (i=0; i <=5 ; i++)
{
//making the program stop so I can see the alert showing and dissappearing
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
ShowAlert(i);
}
});
}
}
});
thread.start();
public void ShowAlert(int i)
{
if (dialog != null)
{
dialog.cancel();
}
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("" + i);
dialog = alertDialog.create();
dialog.show();
}