alertDialog创建登陆界面,需要获取用户输入的用户名和密码,获取控件对象的时候不能像主布局文件那样获得,
需要在onClickListener中获取,代码如下:
1 public boolean onOptionsItemSelected(MenuItem item) {
2 // TODO Auto-generated method stub
3 switch(item.getItemId()){
4 case 1:
5 Intent intent = new Intent();
6 intent.setAction(Intent.ACTION_MAIN);
7 intent.addCategory(Intent.CATEGORY_HOME);
8 startActivity(intent);
9 break;
10 case 2:
11 Toast.makeText(MainActivity.this, "POWER BY BOF", Toast.LENGTH_LONG).show();
12 break;
13 case 3:
14 login();
15 break;
16 }
17 return super.onOptionsItemSelected(item);
18 }
19
20 //用户注册
21 public void login(){
22 /*
23 * 此段代码为重点内容
24 *
25 */
26 LayoutInflater factory = LayoutInflater.from(MainActivity.this);
27 final View v1 = factory.inflate(R.layout.login, null);
28 //创建对话框
29 final Builder alertDialog = new AlertDialog.Builder(this);
30 alertDialog.setTitle("用户登陆");
31 alertDialog.setView(v1);
32 alertDialog.setPositiveButton("登录", new DialogInterface.OnClickListener() {
33
34 @Override
35 public void onClick(DialogInterface dialog, int which) {
36 /*
37 * 下面两行代码为获取dialog中的控件对象,
38 * 和UI布局获取控件对象略有不同,只能在用到alertDialog的地方进行实现
39 */
40 EditText user = (EditText)v1.findViewById(R.id.user);
41 EditText passwd = (EditText)v1.findViewById(R.id.passwd);
42 String userStr = user.getText().toString();
43 String passwdStr = passwd.getText().toString();
44 if(userStr.equals("android") && passwdStr.equals("asdf123..")){
45 Intent intent1 = new Intent(MainActivity.this,HandproActivity.class);
46 startActivity(intent1);
47 }else{
48 Toast.makeText(MainActivity.this, "账号或密码错误,请重新输入", Toast.LENGTH_LONG).show();
49 }
50
51 //Toast.makeText(MainActivity.this, "haha", Toast.LENGTH_LONG).show();
52 }
53 });
54 alertDialog.setNegativeButton("去注册", new DialogInterface.OnClickListener() {
55
56 @Override
57 public void onClick(DialogInterface dialog, int which) {
58 // TODO Auto-generated method stub
59
60 }
61 });
62 alertDialog.create().show();
63 }
64
alertDialog创建登陆界面,判断用户输入,布布扣,bubuko.com
时间: 2024-12-23 23:10:42