android 为什么alertDialog.setButton onclickListner显示找不到合适方法的错误

mwecs4sa  于 2023-02-06  发布在  Android
关注(0)|答案(2)|浏览(97)

主要活动

package com.example.dialog;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AlertDialog alertDialog= new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Term and Conditons");
        alertDialog.setIcon(R.drawable.baseline_info_24);
alertDialog.setMessage("have you read all term and condition");
alertDialog.setButton("yes, I've read",new DialogInterface.OnClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(MainActivity.this, "Tes, you can proceed now..", Toast.LENGTH_SHORT).show();

    }
});
alertDialog.show();
    }
}

错误

C:\Users\anonhake\AndroidStudioProjects\dialog\app\src\main\java\com\example\dialog\MainActivity.java:20: error: no suitable method found for setButton(String,<anonymous OnClickListener>)
alertDialog.setButton("yes, I've read",new DialogInterface.OnClickListener(){
           ^
    method AlertDialog.setButton(int,CharSequence,Message) is not applicable
      (actual and formal argument lists differ in length)
    method AlertDialog.setButton(int,CharSequence,OnClickListener) is not applicable
      (actual and formal argument lists differ in length)
    method AlertDialog.setButton(int,CharSequence,Drawable,OnClickListener) is not applicable
      (actual and formal argument lists differ in length)
bvjxkvbb

bvjxkvbb1#

不要在第一行建立对话框(create()调用),使用AlertDialog.Builder示例,在其上设置“possitive”和“negative”按钮(还有标题、消息等),然后调用create()或更简单的show()
检出样品HERE

// initial builder and msg setup
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Close app?").setTitle("Exit");

// can't close dialog with e.g. back button, must be picked on of buttons
builder.setCancelable(false); 

// buttons setup
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {  
    public void onClick(DialogInterface dialog, int id) {  
        finish(); // closing Activity
    }  
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {  
    public void onClick(DialogInterface dialog, int id) {
    
    }  
});
builder.show();

当点击任何按钮时,对话框将自动关闭,“是”对话框将关闭整个Activity,“否”为空,您将停留在(看起来为空)Activity

jfgube3f

jfgube3f2#

根据错误,看起来你正在使用的带参数类型的方法不存在。所以基本上你有三种选择

1. setButton(int,CharSequence,Message)
 2. setButton(int,CharSequence,OnClickListener)
 3. setButton(int,CharSequence,Drawable,OnClickListener)

相关问题