开发者

AlertDialog does not display when used with a button

开发者 https://www.devze.com 2023-03-22 10:39 出处:网络
I would like to display an alert when my \"save\" button is pressed if the textview fields are left blank.However, I can not get an AlertDialog box to appear within my save button.The same code works

I would like to display an alert when my "save" button is pressed if the textview fields are left blank. However, I can not get an AlertDialog box to appear within my save button. The same code works for the AlertDialog if it is outside of the button. Thanks in advance for any help you can provide. I read several similar questions for none of the solutions are solving my problem. My code is below:

public class MyActivity extends Activity{

...

 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

...

Button saveButton = (Button) findViewById(R.id.data_save);

new AlertDialog.Builder(MyActivity.this)  
        .setMessage("This is a test")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }})
         .show();

saveButton.setOn开发者_JAVA技巧ClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);   
                  builder.setMessage("This is a test 2 ")
                         .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {
                                 dialog.cancel();
                             }
                          })
                          .show();


        }                               
        );


This code works fine for me. If you are getting any sort of exception post it. Try Clean-ing the project and try again.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号