package com.itheima.logindemo; import android.os.Bundle; import android.app.Activity; import android.content.DialogInterface; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private EditText et_pwd; private CheckBox cb_isSave; private Button btn_login; private EditText et_username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //加载界面 setContentView(R.layout.activity_main); et_username = (EditText) findViewById(R.id.et_username); et_pwd = (EditText) findViewById(R.id.et_password); cb_isSave = (CheckBox) findViewById(R.id.cb_isSave); btn_login = (Button) findViewById(R.id.btn_login); //设置点击事件 btn_login.setOnClickListener(new MyListener()); } private class MyListener implements OnClickListener{ @Override public void onClick(View v) { // TODO Auto-generated method stub //当按钮被点击就会走这个方法 //①获取用户输入 String pwd = et_pwd.getText().toString().trim(); String username = et_username.getText().toString().trim(); //②判断输入是否为空 if(TextUtils.isEmpty(username)||TextUtils.isEmpty(pwd)){ //2.1如果为空Toast提示用户 不能为空 Toast.makeText(MainActivity.this, "用户名密码不能为空", Toast.LENGTH_SHORT).show();//上下文是MainActivity }else{ //2.2如果不为空 判断是否保存密码 //③通过checkbox的状态 判断是否保存 boolean checked = cb_isSave.isChecked(); if(checked){ //勾选上了 保存用户名密码 Log.d("MainActivity", "保存用户名:"+username+"密码:"+pwd); } //④执行登录的业务逻辑 Log.d("MainActivity", "开始登录...."); } } } }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <EditText android:id="@+id/et_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入用户名"/> <EditText android:id="@+id/et_password" android:layout_below="@id/et_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:hint="请输入密码"/> <CheckBox android:id="@+id/cb_isSave" android:layout_below="@id/et_password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="勾选保存信息"/> <Button android:id="@+id/btn_login" android:layout_below="@id/cb_isSave" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="登陆" /> </RelativeLayout>