本来不打算写这个的 很简单 可是我调试了好多遍 下面把代码附上
就是点击一个按键 弹出一个简单对话框
package com.example.main;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview=(TextView) findViewById(R.id.textview);
textview.setOnClickListener(onClick);
}
private View.OnClickListener onClick=new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Dialog alertDialog=new AlertDialog.Builder(MainActivity.this).setTitle("是否删除?").setIcon(R.drawable.ic_launcher).setTitle("是否删除").setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
new AlertDialog.Builder(MainActivity.this).setMessage("你已经删除该文件").create().show();
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
new AlertDialog.Builder(MainActivity.this).setMessage("你已经取消删除0删除该文件,删除失败").create().show();
}
}).create();//这必须写create然后在show
//直接写show 有错误
alertDialog.show();
}
};
}
在xml定义一个Textview的id即可
下面是按钮的 代码是一样的
package com.example.main66;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button =(Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Dialog di=new AlertDialog.Builder(MainActivity.this).setTitle("你吃饭了吗")
.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this).setMessage("确认").create().show();
//Toast.makeText(MainActivity.this, "确认", Toast.LENGTH_LONG).show();
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this).setMessage("取消").create().show();
//Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_LONG).show();
}
}).create();
di.show();
}
});
}
}