【问题标题】:Cancel Button in Alert Dialog not working警报对话框中的取消按钮不起作用
【发布时间】:2016-11-02 12:24:57
【问题描述】:

我正在开发 Android 中的警报对话框。警报对话框显示正常, 但是取消按钮无法正常工作:单击取消按钮时,未找到 OnClick 方法“取消对话框”,尽管它位于主活动中,并且我正在将对话框实例传递给该方法。我不知道为什么;因此,任何帮助将不胜感激。

Logcat 显示如下错误:

11-01 21:10:30.111 11217-11217/de.die_web_agenten.www.batprice E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                 Process: de.die_web_agenten.www.batprice, PID: 11217
                                                                                 java.lang.IllegalStateException: Could not find method cancelDialog(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'dialog_cancel'
                                                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
                                                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                                                                                     at android.view.View.performClick(View.java:5198)
                                                                                     at android.view.View$PerformClick.run(View.java:21147)
                                                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                     at android.os.Looper.loop(Looper.java:148)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-01 21:10:34.599 11217-11217/de.die_web_agenten.www.batprice I/Process: Sending signal. PID: 11217 SIG: 9

这是主要活动:

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        openDialog();

        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Contact us", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                Uri uri = Uri.parse("http://www.die-web-agenten.de/en/kontaktaufnahme/");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();

        // Logs 'install' and 'app activate' App Events.
        AppEventsLogger.activateApp(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        // Logs 'app deactivate' App Event.
        AppEventsLogger.deactivateApp(this);
    }

    @Override
    public void onBackPressed() {

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_results) {
            // Handle the camera action
            Intent SecondListActivityIntent = new Intent(MainActivity.this, de.die_web_agenten.www.batprice.SecondListActivity.class);
            MainActivity.this.startActivity(SecondListActivityIntent);

        } else if (id == R.id.nav_map) {

            // Handle the camera action

            Intent MapsActivityIntent = new Intent(MainActivity.this, MapsActivity.class);
            //ListActivity.putExtra("key", value); //Optional parameters
            MainActivity.this.startActivity(MapsActivityIntent);

            //Intent ListActivityIntent = new Intent(MainActivity.this, ListActivity.class);
            //ListActivity.putExtra("key", value); //Optional parameters
            //MainActivity.this.startActivity(ListActivityIntent);

        } else if (id == R.id.nav_results) {
            // Handle the camera action
            Intent ResultsActivityIntent = new Intent(MainActivity.this, de.die_web_agenten.www.batprice.ResultsActivity.class);
            //ListActivity.putExtra("key", value); //Optional parameters
            MainActivity.this.startActivity(ResultsActivityIntent);

        } /*else if (id == R.id.nav_training) {
            // Handle the camera action
            Intent TrainingActivityIntent = new Intent(MainActivity.this, de.die_web_agenten.www.batprice.TrainingActivity.class);
            //ListActivity.putExtra("key", value); //Optional parameters
            MainActivity.this.startActivity(TrainingActivityIntent);

        } */
         else if (id == R.id.nav_share) {
            // Handle the camera action
            Intent AndroidBarcodeQRExampleIntent = new Intent(MainActivity.this, de.die_web_agenten.www.batprice.AndroidBarcodeQrExample.class);
            //ListActivity.putExtra("key", value); //Optional parameters
            MainActivity.this.startActivity(AndroidBarcodeQRExampleIntent);

        } else if (id == R.id.nav_send) {
            // Handle the camera action

                    Uri uri = Uri.parse("http://www.die-web-agenten.de/en/kontaktaufnahme/");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    public void OpenListActivity() {
        Intent SecondListActivityIntent = new Intent(MainActivity.this, de.die_web_agenten.www.batprice.SecondListActivity.class);
        //ListActivity.putExtra("key", value); //Optional parameters
        MainActivity.this.startActivity(SecondListActivityIntent);

    }

    public void openDialog() {
        final Dialog dialog = new Dialog(this); // Context, this, etc.
        dialog.setContentView(R.layout.dialog_demo);
        dialog.setTitle(R.string.dialog_title);
        dialog.show();
    }

    public void cancelDialog(Dialog dialog) {
        dialog.dismiss();
    }

}

这是对应的对话框演示布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/dialog_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="@string/dialog_text"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@id/dialog_info">

        <Button
            android:id="@+id/dialog_cancel"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:text="Cancel"
            android:onClick="cancelDialog"/>

        <Button
            android:id="@+id/dialog_ok"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:text="Check voucher"/>

        <Button
            android:id="@+id/buttonAlert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Show Alert Box" />
    </LinearLayout>
</RelativeLayout>

【问题讨论】:

    标签: android android-alertdialog cancel-button


    【解决方案1】:

    您以错误的方式实施它。你可以这样做

    private Dialog dialog;
    
    public void openDialog() {
    dialog = new Dialog(this); // Context, this, etc.
    dialog.setContentView(R.layout.dialog_demo);
    dialog.setTitle(R.string.dialog_title);
    dialog.show();
    

    }

    public void cancelDialog(View view) {
    dialog.dismiss();
    }
    

    cancelDialog 方法需要 View 类型的参数,而您正试图将其作为 Dialog 传递。这就是您的应用程序崩溃的原因。希望它会帮助你。

    【讨论】:

      【解决方案2】:

      可能是这样的

      Dialog dialog;
      public void openDialog() {
          dialog = new Dialog(this); // Context, this, etc.
          dialog.setContentView(R.layout.dialog_demo);
          dialog.setTitle(R.string.dialog_title);
          dialog.show();
      }
      
      public void cancelDialog() {
          dialog.dismiss();
      }
      

      【讨论】:

        【解决方案3】:

        您的 cancelDialog 方法需要一个 Dialog 类型的参数,而您的错误消息告诉您找不到参数类型为 View 的方法。

        我的 android 时代已经结束了一段时间,但我认为您需要接受 View 作为参数(这是按钮所在的视图)并关闭它,而不是仅仅关闭对话框。

        【讨论】:

          【解决方案4】:

          这很明显,因为如果您在 XML 上的 View 上定义 onClick 以运行方法,则该方法本身将需要 View,这是您在 XML 上定义的 View,同时您传递 Dialog到那个方法。在您的情况下,您传递 Button 而不是 Dialog

          删除

          public void cancelDialog(Dialog dialog) {
              dialog.dismiss();
          }
          

          android:onClick="cancelDialog"
          

          在您的 dialog_cancel 按钮上。 然后将 openDialog 方法编辑成这样:

          public void openDialog() {
              final Dialog dialog = new Dialog(this); // Context, this, etc.
              dialog.setContentView(R.layout.dialog_demo);
              dialog.setTitle(R.string.dialog_title);
              View vCancel = dialog.findViewById(R.id.dialog_cancel);
              vCancel.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      dialog.dismiss();
                  }
              });
              dialog.show();
          }
          

          【讨论】:

          • 谢谢!这很有帮助!
          【解决方案5】:

          试试这个代码

          Dialog dialog;
          public void openDialog() {
              dialog = new Dialog(this); // Context, this, etc.
              dialog.setContentView(R.layout.dialog_demo);
              dialog.setTitle(R.string.dialog_title);
              dialog.show();
          }
          
          public void cancelDialog() { 
              dialog.dismiss();
          }
          

          您将按钮视图传递给cancelDialog(View) 而不是cancelDialog(Dialog v)

          【讨论】:

          • 谢谢!这很有帮助!
          【解决方案6】:

          你应该扩展对话框类并将你的“onclick”方法放在那里。

          这应该对你有帮助:Using onClick attribute in layout xml causes a NoSuchMethodException in Android dialogs

          【讨论】:

          • 谢谢!这很有帮助!
          【解决方案7】:
          This should be able to help:
          
            private void openDialog() {
          
            LayoutInflater layoutInflaterAndroid = LayoutInflater.from(BaseActivity.this);
                  View view = layoutInflaterAndroid.inflate(R.layout.edit_remark_dialog, null);
                  AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BaseActivity.this);
                  alertDialogBuilder.setView(view);
                  final AlertDialog alertDialog = alertDialogBuilder.create();
          
                  Button btnEdit = (Button) view.findViewById(R.id.btn_edit);
                  Button btnDelete = (Button) view.findViewById(R.id.btn_delete);
                  final EditText etRemark = (EditText) view.findViewById(R.id.et_remark);
                  TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
                  TextView tvMessage = (TextView) view.findViewById(R.id.tv_msg);
          
          
                  tvTitle.setText(getResources().getString(R.string.exit_app));
                  tvMessage.setText(getResources().getString(R.string.are_you_sure_want_exit));
                  btnEdit.setText(getResources().getString(R.string.no));
                  btnDelete.setText(getResources().getString(R.string.yes));
                  btnEdit.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
          
                          alertDialog.dismiss();
                      }
                  });
                  btnDelete.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
          
                          finish();
                          alertDialog.dismiss();
                      }
                  });
          
                  alertDialog.show();
          
              }
          

          【讨论】:

            【解决方案8】:

            只在类声明中声明对话框,cancleDialog方法中不需要传递对话框参数。当您显示对话框时,只需调用方法打开对话框,当您关闭对话框时调用 cancleDialog 方法

            Dialog dialog;
            public void openDialog() {
                    dialog = new Dialog(this); // Context, this, etc.
                    dialog.setContentView(R.layout.dialog_demo);
                    dialog.setTitle(R.string.dialog_title);
                    dialog.show();
                }
            
                public void cancelDialog() {
                    dialog.dismiss();
                }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2015-08-27
              • 1970-01-01
              • 2019-04-27
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-01-03
              相关资源
              最近更新 更多