android 模仿qq登录界面EditText下拉框记住账号和密码 editText+popupwindow+sqlite方式实现(附源码)

来源:互联网 发布:数据库第三范式 编辑:程序博客网 时间:2024/05/18 09:14

实现这个功能 在网上找了好多 都没有完整的实现方式,自己就写了一个例子

包括记住账号、记住密码、下拉框选择账号记录和删除账号记录的功能

效果图:

源码资源地址:http://download.csdn.net/detail/wlj32011/4526339

1.创建布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@drawable/default_blank" >    <RelativeLayout        android:id="@+id/login_layout"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:paddingTop="70dip" >        <TextView            android:id="@+id/login_text"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="10dip"            android:text="登录"            android:textColor="#716b60"            android:textSize="20sp" />        <FrameLayout            android:id="@+id/username_layout"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_below="@id/login_text" >            <EditText                android:id="@+id/username"                android:layout_width="300dip"                android:layout_height="50dip"                android:layout_marginTop="5dip"                android:background="@drawable/login_input"                android:hint="请输入号码"                android:inputType="number" >            </EditText>            <ImageButton                android:id="@+id/dropdown_button"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="right|center_vertical"                android:layout_marginRight="5dip"                android:background="@drawable/login_input_arrow"                android:contentDescription="@string/app_name" />        </FrameLayout>        <EditText            android:id="@+id/password"            android:layout_width="300dip"            android:layout_height="50dip"            android:layout_below="@id/username_layout"            android:background="@drawable/login_input"            android:hint="请输入密码"            android:inputType="textPassword" >        </EditText>        <RelativeLayout            android:id="@+id/remember_layout"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_below="@id/password"            android:layout_marginLeft="10dip" >            <CheckBox                android:id="@+id/remember"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:button="@drawable/checkbox_bg1"                android:checked="true"                android:text="记住密码"                android:textAppearance="@android:style/TextAppearance.Small"                android:textColor="#716b60" />        </RelativeLayout>        <Button            android:id="@+id/login"            android:layout_width="300dip"            android:layout_height="50dip"            android:layout_below="@id/remember_layout"            android:background="@drawable/login_selector"            android:text="登录" />    </RelativeLayout></RelativeLayout>

2.数据库辅助类

DBHelper

package com.example.login.database;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import com.example.login.database.DBUser.User;/** * 操作数据库辅助类 *  * @author 2012-8-12 */public class DBHelper {public static final int DB_VERSION = 1;public static final String DB_NAME = "example.db";public static final String USER_TABLE_NAME = "user_table";public static final String[] USER_COLS = { User.USERNAME, User.PASSWORD,User.ISSAVED };private SQLiteDatabase db;private DBOpenHelper dbOpenHelper;public DBHelper(Context context) {this.dbOpenHelper = new DBOpenHelper(context);establishDb();}/** * 打开数据库 */private void establishDb() {if (this.db == null) {this.db = this.dbOpenHelper.getWritableDatabase();}}/** * 插入一条记录 *  * @param map *            要插入的记录 * @param tableName *            表名 * @return 插入记录的id -1表示插入不成功 */public long insertOrUpdate(String userName, String password, int isSaved) {boolean isUpdate = false;String[] usernames = queryAllUserName();for (int i = 0; i < usernames.length; i++) {if (userName.equals(usernames[i])) {isUpdate = true;break;}}long id = -1;if (isUpdate) {id = update(userName, password, isSaved);} else {if (db != null) {ContentValues values = new ContentValues();values.put(User.USERNAME, userName);values.put(User.PASSWORD, password);values.put(User.ISSAVED, isSaved);id = db.insert(USER_TABLE_NAME, null, values);}}return id;}/** * 删除一条记录 *  * @param userName *            用户名 * @param tableName *            表名 * @return 删除记录的id -1表示删除不成功 */public long delete(String userName) {long id = db.delete(USER_TABLE_NAME, User.USERNAME + " = '" + userName+ "'", null);return id;}/** * 更新一条记录 *  * @param *  * @param tableName *            表名 * @return 更新过后记录的id -1表示更新不成功 */public long update(String username, String password, int isSaved) {ContentValues values = new ContentValues();values.put(User.USERNAME, username);values.put(User.PASSWORD, password);values.put(User.ISSAVED, isSaved);long id = db.update(USER_TABLE_NAME, values, User.USERNAME + " = '"+ username + "'", null);return id;}/** * 根据用户名查询密码 *  * @param username *            用户名 * @param tableName *            表名 * @return Hashmap 查询的记录 */public String queryPasswordByName(String username) {String sql = "select * from " + USER_TABLE_NAME + " where "+ User.USERNAME + " = '" + username + "'";Cursor cursor = db.rawQuery(sql, null);String password = "";if (cursor.getCount() > 0) {cursor.moveToFirst();password = cursor.getString(cursor.getColumnIndex(User.PASSWORD));}return password;}/** * 记住密码选项框是否被选中 *  * @param username * @return */public int queryIsSavedByName(String username) {String sql = "select * from " + USER_TABLE_NAME + " where "+ User.USERNAME + " = '" + username + "'";Cursor cursor = db.rawQuery(sql, null);int isSaved = 0;if (cursor.getCount() > 0) {cursor.moveToFirst();isSaved = cursor.getInt(cursor.getColumnIndex(User.ISSAVED));}return isSaved;}/** * 查询所有用户名 *  * @param tableName *            表名 * @return 所有记录的list集合 */public String[] queryAllUserName() {if (db != null) {Cursor cursor = db.query(USER_TABLE_NAME, null, null, null, null,null, null);int count = cursor.getCount();String[] userNames = new String[count];if (count > 0) {cursor.moveToFirst();for (int i = 0; i < count; i++) {userNames[i] = cursor.getString(cursor.getColumnIndex(User.USERNAME));cursor.moveToNext();}}return userNames;} else {return new String[0];}}/** * 关闭数据库 */public void cleanup() {if (this.db != null) {this.db.close();this.db = null;}}/** * 数据库辅助类 */private static class DBOpenHelper extends SQLiteOpenHelper {public DBOpenHelper(Context context) {super(context, DB_NAME, null, DB_VERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL("create table " + USER_TABLE_NAME + " (" + User._ID+ " integer primary key," + User.USERNAME + " text, "+ User.PASSWORD + " text, " + User.ISSAVED + " INTEGER)");}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE_NAME);onCreate(db);}}}

User:

package com.example.login.database;import android.provider.BaseColumns;/** *  * 2012-8-12 */public final class DBUser {public static final class User implements BaseColumns {public static final String USERNAME = "username";public static final String PASSWORD = "password";public static final String ISSAVED = "issaved";}}



3.Activity

package com.example.login.activity;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;import android.widget.ImageButton;import android.widget.ListView;import android.widget.PopupWindow;import android.widget.SimpleAdapter;import android.widget.TextView;import android.widget.Toast;import com.example.login.R;import com.example.login.database.DBHelper;public class MainActivity extends Activity implements OnClickListener {private EditText mUserName;private EditText mPassword;private Button mLoginButton;private ImageButton mDropDown;private DBHelper dbHelper;private CheckBox mCheckBox;private PopupWindow popView;private MyAdapter dropDownAdapter;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initWidget();}private void initWidget() {dbHelper = new DBHelper(this);mUserName = (EditText) findViewById(R.id.username);mPassword = (EditText) findViewById(R.id.password);mLoginButton = (Button) findViewById(R.id.login);mDropDown = (ImageButton) findViewById(R.id.dropdown_button);mCheckBox = (CheckBox) findViewById(R.id.remember);mLoginButton.setOnClickListener(this);mDropDown.setOnClickListener(this);initLoginUserName();}private void initLoginUserName() {String[] usernames = dbHelper.queryAllUserName();if (usernames.length > 0) {String tempName = usernames[usernames.length - 1];mUserName.setText(tempName);mUserName.setSelection(tempName.length());String tempPwd = dbHelper.queryPasswordByName(tempName);int checkFlag = dbHelper.queryIsSavedByName(tempName);if (checkFlag == 0) {mCheckBox.setChecked(false);} else if (checkFlag == 1) {mCheckBox.setChecked(true);}mPassword.setText(tempPwd);}mUserName.addTextChangedListener(new TextWatcher() {@Overridepublic void onTextChanged(CharSequence s, int start, int before,int count) {mPassword.setText("");}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,int after) {}@Overridepublic void afterTextChanged(Editable s) {}});}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.login:String userName = mUserName.getText().toString();String password = mPassword.getText().toString();if (mCheckBox.isChecked()) {dbHelper.insertOrUpdate(userName, password, 1);} else {dbHelper.insertOrUpdate(userName, "", 0);}Toast.makeText(this, "记录已经保存", Toast.LENGTH_LONG).show();break;case R.id.dropdown_button:if (popView != null) {if (!popView.isShowing()) {popView.showAsDropDown(mUserName);} else {popView.dismiss();}} else {// 如果有已经登录过账号if (dbHelper.queryAllUserName().length > 0) {initPopView(dbHelper.queryAllUserName());if (!popView.isShowing()) {popView.showAsDropDown(mUserName);} else {popView.dismiss();}} else {Toast.makeText(this, "无记录", Toast.LENGTH_LONG).show();}}break;}}private void initPopView(String[] usernames) {List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();for (int i = 0; i < usernames.length; i++) {HashMap<String, Object> map = new HashMap<String, Object>();map.put("name", usernames[i]);map.put("drawable", R.drawable.xicon);list.add(map);}dropDownAdapter = new MyAdapter(this, list, R.layout.dropdown_item,new String[] { "name", "drawable" }, new int[] { R.id.textview,R.id.delete });ListView listView = new ListView(this);listView.setAdapter(dropDownAdapter);popView = new PopupWindow(listView, mUserName.getWidth(),ViewGroup.LayoutParams.WRAP_CONTENT, true);popView.setFocusable(true);popView.setOutsideTouchable(true);popView.setBackgroundDrawable(getResources().getDrawable(R.drawable.white));// popView.showAsDropDown(mUserName);}class MyAdapter extends SimpleAdapter {private List<HashMap<String, Object>> data;public MyAdapter(Context context, List<HashMap<String, Object>> data,int resource, String[] from, int[] to) {super(context, data, resource, from, to);this.data = data;}@Overridepublic int getCount() {return data.size();}@Overridepublic Object getItem(int position) {return position;}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(final int position, View convertView,ViewGroup parent) {System.out.println(position);ViewHolder holder;if (convertView == null) {holder = new ViewHolder();convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.dropdown_item, null);holder.btn = (ImageButton) convertView.findViewById(R.id.delete);holder.tv = (TextView) convertView.findViewById(R.id.textview);convertView.setTag(holder);} else {holder = (ViewHolder) convertView.getTag();}holder.tv.setText(data.get(position).get("name").toString());holder.tv.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String[] usernames = dbHelper.queryAllUserName();mUserName.setText(usernames[position]);mPassword.setText(dbHelper.queryPasswordByName(usernames[position]));popView.dismiss();}});holder.btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String[] usernames = dbHelper.queryAllUserName();if (usernames.length > 0) {dbHelper.delete(usernames[position]);}String[] newusernames = dbHelper.queryAllUserName();if (newusernames.length > 0) {initPopView(newusernames);popView.showAsDropDown(mUserName);} else {popView.dismiss();popView = null;}}});return convertView;}}class ViewHolder {private TextView tv;private ImageButton btn;}@Overrideprotected void onStop() {super.onStop();dbHelper.cleanup();}}

4.下拉框布局

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="horizontal"    android:paddingBottom="10dip"    android:paddingTop="10dip" >    <ImageButton        android:id="@+id/delete"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_centerVertical="true"        android:layout_marginRight="10dip"        android:background="@drawable/xicon"        android:contentDescription="@string/app_name" />    <TextView        android:id="@+id/textview"        style="?android:attr/dropDownItemStyle"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_toLeftOf="@id/delete"        android:singleLine="true"        android:textAppearance="?android:attr/textAppearanceSmallInverse" /></RelativeLayout>