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

时间:2011-09-06 16:49:27

标签: 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();
                } 
            }

        }
    );
  }

} 

2 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:1)

不要忘记先导入android.app.AlertDialog。

     AlertDialog alert = new AlertDialog.Builder(this).create();
            alert.setTitle("Error");
            alert.setMessage("Sorry, your device doesn't support flash light!");
            alert.setButton(Dialog.BUTTON_POSITIVE,"OK",new DialogInterface.OnClickListener(){

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });

alert.show();