安卓 AlertDialog按钮不工作,也不会关闭
我有一个对话,应该是两个玩家之间的决斗。它显示了一个决斗的图像,三秒钟后,由于计时器的作用,它显示了一个“砰”的图像。当“砰”的图像出现时,玩家必须按下“砰”按钮,溃烂玩家获胜。我的问题是按钮上的侦听器不工作,我无法关闭alertDialog。这是密码
package com.example.root.gbu;
import 安卓.app.Activity;
import 安卓.app.AlertDialog;
import 安卓.content.Context;
import 安卓.content.DialogInterface;
import 安卓.os.SystemClock;
import 安卓.widget.ImageView;
public class DuelFrame {
private Context context;
private long startTime;
private long endTime;
private boolean timeToShot=false;
private ImageView image;
private AlertDialog alertDialog;
public DuelFrame(String enemy, Context context){
this.context = context;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Duel against " + enemy);
image = new ImageView(context);
image.setImageResource(R.drawable.duel_start);
builder.setView(image);
builder.setNegativeButton("BANG",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
System.out.println("********************BANG PREMUTO*************************");
if(timeToShot) {
endTime = SystemClock.elapsedRealtimeNanos();
ConnectionStream.getOut().println("TIME:" + String.valueOf(endTime - startTime));
}
else
ConnectionStream.getOut().println("TIME:LOSE");
}
});
alertDialog = builder.create();
}
public void start(){
((Activity)context).runOnUiThread(new Runnable(){//mostro la finestra
@Override
public void run(){
alertDialog.show();
}
});
new java.util.Timer().schedule(//timer per cambiare l'immagine
new java.util.TimerTask() {
@Override
public void run() {
((Activity)context).runOnUiThread(new Runnable(){
@Override
public void run(){
image.getLayoutParams().height = image.getHeight();
image.getLayoutParams().width = image.getWidth();
image.setImageResource(R.drawable.bang);
startTime = SystemClock.elapsedRealtimeNanos();
timeToShot = true;
}
});
}
}, 3000);
}
public void cancel(){
((Activity)context).runOnUiThread(new Runnable(){
@Override
public void run(){
alertDialog.dismiss();
}
});
}
}
所以我需要修复onClickListener和cancel()函数
# 1 楼答案
使用此警报框。这是我的工作
# 2 楼答案
你需要打电话给警察
showDialog(int)
方法。 然后重写该方法onCreateDialog(int)
在这个对话框中,创建对话框并设置正负按钮,然后它就会工作尽管这种方式已被弃用。现在应该使用片段。但你还是可以试一试
检查此链接:https://developer.android.com/guide/topics/ui/dialogs.html