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

标签 android android-layout projects-and-solutions

我正在为 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();
                } 
            }

        }
    );
  }

} 

最佳答案

问题是 OnClickListener 中的 this 需要限定。尝试使用

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

关于android - android 程序中的 AlertDialog.Builder 显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7323370/

相关文章:

android - 如何在 ANDROID 中实现/调试传感器驱动程序

Android - 覆盖 android 布局文件中的样式

android - 如何将 GridLayout.Spec 用于扩展多行的列?

android - 如何修复此布局错误。按钮未正确放置?

C++ 避免或管理 MSVC 中的循环项目依赖

c++ - VC++ "Exclude Directories"项目设置实际上是做什么的?

c# - 为 amazon web services sdk 添加对 visual studio 项目的引用

android - 在 Kotlin 中的原始类型属性上不允许使用 lateinit 修饰符

java - 无法为Android build.gradle文件添加其他Maven存储库

android - 用于蓝牙设备发现的 BroadcastReceiver 适用于一台设备,但不适用于另一台设备