android程序中的AlertDialog.Builder显示错误

kir*_*ran 1 android projects-and-solutions android-layout

我正在为android中的应用程序构建一个登录页面.但是在测试它时会在AlertDialog.Builder中给出错误,说它没有定义.我在其他应用程序中使用它并且工作得很好.提前致谢.这是代码:

package project.login;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    Button launch = (Button)findViewById(R.id.login_button);

    launch.setOnClickListener( new OnClickListener ()
    {
        public void onClick(View view)
        {   EditText usernameEditText = (EditText) findViewById(R.id.username);
            EditText passwordEditText = (EditText) findViewById(R.id.password);

            String sUsername = usernameEditText.getText().toString();
            String sPassword = passwordEditText.getText().toString();

            if(usernameEditText == null || passwordEditText == null) {
                new AlertDialog.Builder(this)
                .setTitle("Error")
                .setMessage("You can't let the fields empty")
                .show();
                } 
            }

        }
    );
  }

} 
Run Code Online (Sandbox Code Playgroud)

Jus*_*ler 7

问题是您的OnClickListener内部需要限定.尝试使用

new AlertDialog.Builder(LoginActivity.this)
            .setTitle("Error")
            .setMessage("You can't let the fields empty")
            .show();
Run Code Online (Sandbox Code Playgroud)