1. MainActivity
public class MainActivity extends AppCompatActivity { private Button mybutton = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.mybutton = (Button) super.findViewById(R.id.mybutton); this.mybutton.setOnClickListener(new OnClickListenerImp()); } private class OnClickListenerImp implements OnClickListener { @Override public void onClick(View v) { MainActivity.this.exitDialog(); } } private void exitDialog() { Dialog dialog = new AlertDialog.Builder(MainActivity.this) .setTitle("program back?") .setMessage("are you sure to exit this program?") .setPositiveButton("sure", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MainActivity.this.finish(); //end of program } }).setNegativeButton("cancel", //add cancel button new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).create(); //create Dialog dialog.show(); //show Dialog } }
2. activity_main.xml
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/mytext" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="60dp" android:text="hello" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="delete" android:id="@+id/mybutton" android:layout_below="@+id/mytext" android:layout_centerHorizontal="true" android:layout_marginTop="55dp" />
时间: 2024-10-05 02:33:40