android 通讯录的实现
通讯录,能实现简单的增加联系人、删除联系人、设置私密账号、点击item可以对该联系人进行通话、调用系统的拨号界面、备份数据、恢复数据简单的功能!然后呢,接着咱就可以看看实现的过程
首先先看一下布局
1。欢迎界面的布局startimage.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/startimage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:src="@drawable/welcome" >
</ImageView>
2.接着是主界面main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg"
>
<FrameLayout
android:id="@+id/list_ll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="@+id/lv_userlist"
android:layout_above="@+id/gv_buttom_menu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<!-- <TextView
android:id="@+id/tvLetter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/textviewbg"
android:gravity="center"
android:maxWidth="50dp"
android:minWidth="50dp"
android:textColor="#FF6100"
android:textSize="50sp" />
<com.wang.A_Z.ListA_Z
android:id="@+id/myView"
android:layout_width="30dip"
android:layout_height="fill_parent"
android:layout_gravity="right" /> -->
</FrameLayout>
<GridView
android:id="@+id/gv_buttom_menu"
android:layout_height="80dp"
android:layout_width="fill_parent"
android:layout_alignParentBottom="true"
android:visibility="gone">
</GridView>
<LinearLayout
android:id="@+id/ll_search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_above="@+id/gv_buttom_menu"
android:visibility="gone">
<EditText
android:id="@+id/et_search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入查询的号码或姓名"
android:textSize="18dp">
</EditText>
</LinearLayout>
</RelativeLayout>
3.接着呢,就是增加联系人的界面布局addnewcontacts.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ScrollView android:layout_weight="4"
android:id="@+id/ScrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/widget205"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
>
<ImageButton
android:id="@+id/image_button"
android:layout_width="60px"
android:layout_height="60px"
android:src="@drawable/icon"
android:scaleType="centerCrop"
>
</ImageButton>
<EditText
android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:hint="姓名"
android:gravity="top"
android:layout_gravity="center_vertical"
/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="手机:"
android:textSize="20dp" />
<EditText
android:id="@+id/mobilephone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:gravity="top"
android:hint="手机"
android:phoneNumber="true" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="办公室电话:"
android:textSize="20dp" />
<EditText
android:id="@+id/officephone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:phoneNumber="true"
android:hint="办公室电话"
android:gravity="top" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="家庭电话:"
android:textSize="20dp" />
<EditText
android:id="@+id/familyphone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:phoneNumber="true"
android:hint="家庭电话"
android:gravity="top" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="职务职称:"
android:textSize="20dp" />
<EditText
android:id="@+id/position"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:hint="职务职称"
android:gravity="top" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="单位名称:"
android:textSize="20dp" />
<EditText
android:id="@+id/company"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:hint="单位名称"
android:gravity="top" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="地址:"
android:textSize="20dp" />
<EditText
android:id="@+id/address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:hint="地址"
android:gravity="top" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="邮政编码:"
android:textSize="20dp" />
<EditText
android:id="@+id/zipcode"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:hint="邮政编码"
android:gravity="top" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="E-mail:"
android:textSize="20dp" />
<EditText
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:hint="E-mail" android:gravity="top" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="其他联系方式:"
android:textSize="20dp" />
<EditText
android:id="@+id/othercontact"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:hint="其他联系方式"
android:gravity="top" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="备注:"
android:textSize="20dp" />
<EditText android:id="@+id/remark"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:hint="备注" android:gravity="top" />
</LinearLayout>
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<Button
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="保存"/>
<Button
android:id="@+id/btn_return"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="返回"/>
</LinearLayout>
</LinearLayout>
4.接着是图片选择的对话框界面的imageswitch.xml的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget34"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="110px"
android:layout_alignParentLeft="true"
android:layout_marginTop="10px" >
</Gallery>
<ImageSwitcher
android:id="@+id/imageswitch"
android:layout_width="90px"
android:layout_height="90px"
android:layout_alignBottom="@+id/gallery"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ImageSwitcher>
</RelativeLayout>
5.接着是list列表的界面listitem.xml的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget33"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/user_image"
android:layout_width="50px"
android:layout_height="53px"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ImageView>
<LinearLayout
android:id="@+id/linerlayout"
android:layout_width="fill_parent"
android:layout_height="53px"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/user_image"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="25px"
android:orientation="horizontal" >
<TextView
android:id="@+id/tv_showname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top"
android:text="姓名:"
android:textColor="#000000"
android:textSize="17sp" />
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="7"
android:gravity="left"
android:textColor="#000000"
android:textSize="17sp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="25px"
android:orientation="horizontal" >
<TextView
android:id="@+id/tv_showmobilephone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="手机:"
android:textColor="#000000"
android:textSize="17sp" />
<TextView
android:id="@+id/tv_mobilephone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="7"
android:gravity="left"
android:textColor="#000000"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
<ImageView
android:id="@+id/user_mark"
android:layout_width="60px"
android:layout_height="15px"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="@drawable/checkmark"
android:visibility="gone" />
</RelativeLayout>
6.接下来是点击menu键的item_menu.xml的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout_Item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dip" >
<ImageView
android:id="@+id/item_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" >
</ImageView>
<TextView
android:id="@+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/item_image"
android:layout_centerHorizontal="true" >
</TextView>
</RelativeLayout>
7.然后是在点击menu键后,点击item_menu上的监听事件查找电话号码的numchoose.xml 的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget28"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_numchoose"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="请选择一个号码"
android:textSize="17sp"
android:typeface="serif" >
</TextView>
<ListView
android:id="@+id/num_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
8.接着是在点击menu键后,点击item_menu上的监听事件管理通讯录的监听事件main_menu_grid.xml的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<GridView
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="2"
android:verticalSpacing="10dip"
android:horizontalSpacing="10dip"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</LinearLayout>
9.接着是在点击menu键后,点击item_menu上的监听事件管理备份文件夹的名称enterfilename.xml的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget29"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_enter_file_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="请输入备份文件的文件名\n该文件该置于SD卡的根目录zpContact文件夹下" >
</TextView>
<EditText
android:id="@+id/et_enter_file_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</EditText>
</LinearLayout>
10.接着是一个备份时候进度条的布局backup_progress.xml的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget29"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="@+id/pb_backup"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ProgressBar>
<Button
android:id="@+id/btn_backuup_ok"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="OK"
android:visibility="gone" >
</Button>
</LinearLayout>
11.接着呢就是5s钟的欢迎界面 startAnimation.java
package com.wang.Activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
public class startAnimation extends Activity {
ImageView startimage;
AlphaAnimation startAnimation;
protected void onCreate(Bundle savedInstanceState) {
// 去除标题
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// 取消状态栏,充满全屏
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.startimage);
startimage = (ImageView) findViewById(R.id.startimage);
// 设置动画的渐变效果逐渐增强
startAnimation = new AlphaAnimation(0.0f, 1.0f);
// 设置动画显示的时间为3s
startAnimation.setDuration(5000);
// 开始动画效果
startimage.startAnimation(startAnimation);
// 为动画效果设置监听事件
startAnimation.setAnimationListener(new AnimationListener() {
// ka开始
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
// 重复
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
// 动画结束
@Override
public void onAnimationEnd(Animation animation) {
// 声明一个意图,启动一个新的Activity
Intent intent = new Intent(startAnimation.this,
AddressPhoneBookDemoActivity.class);
// 启动新的Activity
startActivity(intent);
}
});
// 当点击图片的时候也可以进行跳转
startimage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(startAnimation.this,
AddressPhoneBookDemoActivity.class);
// 启动新的Activity
startActivity(intent);
}
});
}
}
12.然后就是跳转到主界面实现过程AddressPhoneBookDemoActivity.java
package com.wang.Activity;
import java.util.ArrayList;
import java.util.HashMap;
import com.wang.Db.DBHelper;
import com.wang.UserInfo.UserInfo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
public class AddressPhoneBookDemoActivity extends Activity {
// 显示所有数据的ListView
ListView lv;
ArrayList list;
// 拥有所有数据的Adapter
SimpleAdapter adapter;
// 屏幕下方的工具栏
GridView bottomMenuGrid;
// 主菜单的布局
GridView mainMenuGrid;
// 主菜单的视图
View mainMenuView;
// 装搜索框的linearlayout,默认情况下visibility=gone
LinearLayout searchLinearout;
FrameLayout mainLinearLayout;
// 搜索框
EditText et_search;
EditText et_enter_file_name;
// 主菜单的对话框
AlertDialog mainMenuDialog;
// 确认对话框
AlertDialog confirmDialog;
// 进度条对话框
AlertDialog progressDialog;
// 输入文件名的对话框
AlertDialog enterFileNameDialog;
// 表示保密状态
boolean privacy = false;
// 存储标记的数目
int markedNum;
// 存储标记条目的_id号
ArrayList<Integer> deleteId;
// 关键界面的文字
String[] main_menu_itemName = { "显示所有", "删除所有", "备份数据", "还原数据", };
// 管理界面的图片资源
int[] main_menu_itemSource = { R.drawable.showall, R.drawable.delete,
R.drawable.menu_backup, R.drawable.menu_restore, };
String[] bottom_menu_itemName = { "增加", "查找", "删除", "管理", "拨号" };
String fileName;
// menu 的图片资源
int[] bottom_menu_itemSource = { R.drawable.addphone, R.drawable.search,
R.drawable.delete, R.drawable.manager, R.drawable.callphone };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 去除标题
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// 取消状态栏,充满全屏
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
// 实例化组件
mainLinearLayout = (FrameLayout) findViewById(R.id.list_ll);
DBHelper helper = new DBHelper(this);
// 打开数据库,就打开这一次,因为Helper中的SQLiteDatabase是静态的。
helper.openDatabase();
// 拿到所有保密状态为privacy的用户的list
list = helper.getAllUser(privacy);
lv = (ListView) findViewById(R.id.lv_userlist);
// 当通讯录中没有信息的时候
if (list.size() == 0) {
Drawable nodata_bg = getResources().getDrawable(
R.drawable.nodata_bg);
mainLinearLayout.setBackgroundDrawable(nodata_bg);
setTitle("没有查到任何数据");
}
// 将数据与adapter集合起来
adapter = new SimpleAdapter(this, list, R.layout.listitem,
new String[] { "imageid", "name", "mobilephone" }, new int[] {
R.id.user_image, R.id.tv_name, R.id.tv_mobilephone });
// 将整合好的adapter交给listview,显示给用户看
lv.setAdapter(adapter);
// 当点击item时候,调用系统进行拨号
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// 得到item位置
HashMap item = (HashMap) arg0.getItemAtPosition(arg2);
// 得到item上的手机号
String number = String.valueOf(item.get("mobilephone"))
.toString();
// 声明一个意图,调用系统的打电话程序
Intent intent = new Intent();
intent.setAction("android.intent.action.CALL");
// 调用系统打电话必须+tel:
intent.setData(Uri.parse("tel:" + number));
startActivity(intent);
}
});
// 设置ListView的背景为透明
lv.setCacheColorHint(Color.TRANSPARENT);
// 长按时间处理可以选中这样才可以删除联系人
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if (deleteId == null) {
deleteId = new ArrayList<Integer>();
}
// 得到item的位置 _id
HashMap item = (HashMap) arg0.getItemAtPosition(arg2);
Integer _id = Integer.parseInt(String.valueOf(item.get("_id")));
RelativeLayout r = (RelativeLayout) arg1;
ImageView markedView = (ImageView) r.getChildAt(2);
if (markedView.getVisibility() == View.VISIBLE) {
markedView.setVisibility(View.GONE);
deleteId.remove(_id);
} else {
markedView.setVisibility(View.VISIBLE);
deleteId.add(_id);
}
return true;
}
});
// 为list添加item设置背景颜色
Drawable itembg = getResources().getDrawable(R.drawable.itembg);
lv.setSelector(itembg);
}
/*****
* 点击menu键的处理事件
*
* *
**/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
loadBottomMenu();
if (bottomMenuGrid.getVisibility() == View.VISIBLE) {
if (searchLinearout != null
&& searchLinearout.getVisibility() == View.VISIBLE) {
searchLinearout.setVisibility(View.GONE);
}
bottomMenuGrid.setVisibility(View.GONE);
} else {
bottomMenuGrid.setVisibility(View.VISIBLE);
}
}
return super.onKeyDown(keyCode, event);
}
/*****
* 底部menu的item的处理
*
* *
**/
private void loadBottomMenu() {
if (bottomMenuGrid == null) {
// 设置menuitem的布局,实力化组件
bottomMenuGrid = (GridView) findViewById(R.id.gv_buttom_menu);
// 设置背景
bottomMenuGrid.setBackgroundResource(R.drawable.item);
// 设置每行列数
bottomMenuGrid.setNumColumns(5);
// 位置居中
bottomMenuGrid.setGravity(Gravity.CENTER);
// 垂直间隔
bottomMenuGrid.setVerticalSpacing(10);
// 水平间隔
bottomMenuGrid.setHorizontalSpacing(10);
// 设置菜单Adapter
bottomMenuGrid.setAdapter(getMenuAdapter(bottom_menu_itemName,
bottom_menu_itemSource));
// / 监听底部菜单menu选项 的时间
bottomMenuGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int id,
long arg3) {
switch (id) {
case 0: {
// 如果查找框不为空,并且查找框可见,则设置为不可见
if (searchLinearout != null
&& searchLinearout.getVisibility() == View.VISIBLE) {
searchLinearout.setVisibility(View.GONE);
}
if (bottomMenuGrid.getVisibility() == View.VISIBLE) {
bottomMenuGrid.setVisibility(View.GONE);
}
// 跳转到添加联系人的界面
Intent intent = new Intent(
AddressPhoneBookDemoActivity.this,
AddNewContacts.class);
startActivityForResult(intent, 3);
break;
}
case 1:
// 调用处理查找联系人的方法
loadSearchLinearout();
// ,并且查找框可见,则设置为不可见
if (searchLinearout.getVisibility() == View.VISIBLE) {
searchLinearout.setVisibility(View.GONE);
} else {
searchLinearout.setVisibility(View.VISIBLE);
// 把后面的查找按钮做焦点
et_search.requestFocus();
et_search.selectAll();
}
break;
case 2:
// 删除联系人的方法
// 如果查找框不为空,并且查找框可见,则设置为不可见
if (searchLinearout != null
&& searchLinearout.getVisibility() == View.VISIBLE) {
searchLinearout.setVisibility(View.GONE);
}
if (deleteId == null || deleteId.size() == 0) {
Toast.makeText(AddressPhoneBookDemoActivity.this,
"亲,没有标记任何记录\n长按一条记录即可标记!!",
Toast.LENGTH_LONG).show();
} else {
// 新建一个警告的对话框
new AlertDialog.Builder(
AddressPhoneBookDemoActivity.this)
.setTitle(
"确定要删除标记的" + deleteId.size()
+ "条记录吗?")
.setPositiveButton(
"确定",
// 确定按钮设置监听事件
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
DBHelper helper = new DBHelper(
AddressPhoneBookDemoActivity.this);
// 调用数据库的删除函数进行删除记录
helper
.deleteMarked(deleteId);
// 重置视图
list = helper
.getAllUser(privacy);
// 声明一个适配器对象
adapter = new SimpleAdapter(
AddressPhoneBookDemoActivity.this,
list,
R.layout.listitem,
new String[] {
"imageid",
"name",
"mobilephone" },
new int[] {
R.id.user_image,
R.id.tv_name,
R.id.tv_mobilephone });
lv.setAdapter(adapter);
deleteId.clear();
}
}).setNegativeButton("取消", null)
.create().show();
}
break;
case 3:
// 管理的界面
// 如果查找框不为空,并且查找框可见,则设置为不可见
if (searchLinearout != null
&& searchLinearout.getVisibility() == View.VISIBLE) {
searchLinearout.setVisibility(View.GONE);
}
// 调用loadMainMenuDialog的方法实现
loadMainMenuDialog();
mainMenuDialog.show();
break;
case 4:
// 调用系统的打电话的界面
Intent intent = new Intent(
"android.intent.action.CALL_BUTTON");
startActivity(intent);
break;
}
}
});
}
}
/*****
* 底部管理 功能的实现方法
*
* *
**/
private void loadMainMenuDialog() {
if (mainMenuDialog == null) {
// 获得LayoutInflater从给定的上下文
LayoutInflater inflater = LayoutInflater.from(this);
mainMenuView = inflater.inflate(R.layout.main_menu_grid, null);
// 根据主菜单视图,创建主菜单对话框
mainMenuDialog = new AlertDialog.Builder(this)
.setView(mainMenuView).create();
// 实例化组件
mainMenuGrid = (GridView) mainMenuView.findViewById(R.id.gridview);
// 根据主菜单视图,获得视图文件中的GridView,然后再往里面放Adapter
SimpleAdapter menuAdapter = getMenuAdapter(main_menu_itemName,
main_menu_itemSource);
mainMenuGrid.setAdapter(menuAdapter);
// 设置管理界面的响应点击事件
mainMenuGrid.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
switch (arg2) {
case 0: {
// 显示所有数据
DBHelper helper = new DBHelper(
AddressPhoneBookDemoActivity.this);
list = helper.getAllUser(privacy);
adapter = new SimpleAdapter(
AddressPhoneBookDemoActivity.this, list,
R.layout.listitem, new String[] { "imageid",
"name", "mobilephone" }, new int[] {
R.id.user_image, R.id.tv_name,
R.id.tv_mobilephone });
lv.setAdapter(adapter);
mainMenuDialog.dismiss();
break;
}
case 1: {
// 是否删除所有数据
// 创建一个对话框
AlertDialog.Builder builder = new AlertDialog.Builder(
AddressPhoneBookDemoActivity.this);
confirmDialog = builder.create();
builder.setTitle("是否删除所有!?");
builder.setPositiveButton("确定",
// 确定按钮的监听事件
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
DBHelper helper = new DBHelper(
AddressPhoneBookDemoActivity.this);
// 调用删除函数删除所有的数据
helper.deleteAll(0);
list = helper.getAllUser(privacy);
adapter = new SimpleAdapter(
AddressPhoneBookDemoActivity.this,
list,
R.layout.listitem,
new String[] { "imageid",
"name", "mobilephone" },
new int[] { R.id.user_image,
R.id.tv_name,
R.id.tv_mobilephone });
lv.setAdapter(adapter);
mainMenuDialog.dismiss();
}
});
builder.setNegativeButton("取消",
// 取消按钮的监听事件
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// 对话框消失
confirmDialog.dismiss();
}
});
builder.create().show();
break;
}
case 2: {
// 备份通讯录的处理
// 对话框消失,重新新建一个对话框
mainMenuDialog.dismiss();
new AlertDialog.Builder(
AddressPhoneBookDemoActivity.this)
.setTitle("是否需要备份记录到SD卡?")
.setPositiveButton("确定",
// 确定按钮的监听事件
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int which) {
LayoutInflater inflater = LayoutInflater
.from(AddressPhoneBookDemoActivity.this);
// 获得一个新的视图层次从指定的xml资源
View backup_view = inflater
.inflate(
R.layout.backup_progress,
null);
// 进度对话框显示
progressDialog = new AlertDialog.Builder(
AddressPhoneBookDemoActivity.this)
.setTitle("备份正在进行中...")
.setView(backup_view)
.create();
progressDialog.show();
DBHelper helper = new DBHelper(
AddressPhoneBookDemoActivity.this);
// 调用数据库进行备份
helper.backupData(privacy);
ProgressBar bar = (ProgressBar) backup_view
.findViewById(R.id.pb_backup);
Button btn_backup_ok = (Button) backup_view
.findViewById(R.id.btn_backuup_ok);
bar.setMax(list.size());
for (int i = 0; i <= list
.size(); i++) {
bar.setProgress(i);
}
// 进度对话框提示一下
progressDialog
.setTitle("备份完成!一共 "
+ list.size()
+ " 条记录");
btn_backup_ok
.setVisibility(View.VISIBLE);
// ok按钮 的监听事件
btn_backup_ok
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(
View v) {
progressDialog
.dismiss();
mainMenuDialog
.dismiss();
}
});
}
}).setNegativeButton("取消", null)
.create()
.show();
break;
}
case 3: {
// 还原数据的处理
LayoutInflater layoutInflater = LayoutInflater
.from(AddressPhoneBookDemoActivity.this);
View enterFileNameView = layoutInflater.inflate(
R.layout.enterfilename, null);
// 还原备份的对话框
enterFileNameDialog = new AlertDialog.Builder(
AddressPhoneBookDemoActivity.this).setView(
enterFileNameView)
.setNegativeButton("取消", null)
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
DBHelper helper = new DBHelper(
AddressPhoneBookDemoActivity.this);
// 得到备份数据的文件夹
fileName = et_enter_file_name
.getText().toString();
if (helper.findFile(fileName)) {
new AlertDialog.Builder(
AddressPhoneBookDemoActivity.this)
.setTitle("请选择方式")
.setPositiveButton(
"覆盖",
// 覆盖数据的方法处理
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
DBHelper helper = new DBHelper(
AddressPhoneBookDemoActivity.this);
// 删除所有联系人
helper
.deleteAll(0);
// 恢复备份的联系人方法
helper
.restoreData(fileName);
// 显示所有联系人的方法
list = helper
.getAllUser(privacy);
adapter = new SimpleAdapter(
AddressPhoneBookDemoActivity.this,
list,
R.layout.listitem,
new String[] {
"imageid",
"name",
"mobilephone" },
new int[] {
R.id.user_image,
R.id.tv_name,
R.id.tv_mobilephone });
LayoutInflater li = LayoutInflater
.from(AddressPhoneBookDemoActivity.this);
View backup_view = li
.inflate(
R.layout.backup_progress,
null);
// 创建备份还原的数据对话框
progressDialog = new AlertDialog.Builder(
AddressPhoneBookDemoActivity.this)
.setTitle(
"正在还原数据...")
.setView(
backup_view)
.create();
progressDialog
.show();
ProgressBar bar = (ProgressBar) backup_view
.findViewById(R.id.pb_backup);
Button btn_backup_ok = (Button) backup_view
.findViewById(R.id.btn_backuup_ok);
bar
.setMax(list
.size());
for (int i = 0; i <= list
.size(); i++) {
bar
.setProgress(i);
}
progressDialog
.setTitle("还原完成!一共还原了 "
+ list
.size()
+ " 条记录");
btn_backup_ok
.setVisibility(View.VISIBLE);
btn_backup_ok
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(
View v) {
progressDialog
.dismiss();
mainMenuDialog
.dismiss();
if (list
.size() != 0) {
mainLinearLayout
.setBackgroundDrawable(null);
}
lv
.setAdapter(adapter);
}
});
}
})
// 添加按钮的监听事件
.setNegativeButton(
"添加",
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int which) {
DBHelper helper = new DBHelper(
AddressPhoneBookDemoActivity.this);
int preNum = list
.size();
helper
.restoreData(fileName);
list = helper
.getAllUser(privacy);
adapter = new SimpleAdapter(
AddressPhoneBookDemoActivity.this,
list,
R.layout.listitem,
new String[] {
"imageid",
"name",
"mobilephone" },
new int[] {
R.id.user_image,
R.id.tv_name,
R.id.tv_mobilephone });
LayoutInflater li = LayoutInflater
.from(AddressPhoneBookDemoActivity.this);
View backup_view = li
.inflate(
R.layout.backup_progress,
null);
progressDialog = new AlertDialog.Builder(
AddressPhoneBookDemoActivity.this)
.setTitle(
"正在还原数据...")
.setView(
backup_view)
.create();
progressDialog
.show();
ProgressBar bar = (ProgressBar) backup_view
.findViewById(R.id.pb_backup);
Button btn_backup_ok = (Button) backup_view
.findViewById(R.id.btn_backuup_ok);
bar
.setMax(list
.size());
for (int i = 0; i <= list
.size(); i++) {
bar
.setProgress(i);
}
progressDialog
.setTitle("还原完成!一共还原了 "
+ (list
.size() - preNum)
+ " 条记录");
btn_backup_ok
.setVisibility(View.VISIBLE);
btn_backup_ok
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(
View v) {
progressDialog
.dismiss();
mainMenuDialog
.dismiss();
lv
.setAdapter(adapter);
}
});
}
})
// 取消按钮是监听事件
.setNeutralButton(
"取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int which) {
}
}).create()
.show();
} else {
// 如果文件夹找不到提示一下
Toast
.makeText(
enterFileNameDialog
.getContext(),
"找不到备份文件",
Toast.LENGTH_LONG)
.show();
}
}
}).create();
et_enter_file_name = (EditText) enterFileNameView
.findViewById(R.id.et_enter_file_name);
et_enter_file_name.setText("comm_data");
et_enter_file_name.requestFocus();
et_enter_file_name.selectAll();
enterFileNameDialog.show();
adapter = new SimpleAdapter(
AddressPhoneBookDemoActivity.this, list,
R.layout.listitem, new String[] { "imageid",
"name", "mobilephone" }, new int[] {
R.id.user_image, R.id.tv_name,
R.id.tv_mobilephone });
lv.setAdapter(adapter);
// 显示所有数据
mainMenuDialog.dismiss();
break;
}
}
}
});
}
}
/*****
* 查找联系人数据的处理函数
*
* *
**/
private void loadSearchLinearout() {
if (searchLinearout == null) {
// 实力化组件
searchLinearout = (LinearLayout) findViewById(R.id.ll_search);
et_search = (EditText) findViewById(R.id.et_search);
// 查找的编辑框设置监听事件
et_search.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
// 声明一个查找的内容
String condition = et_search.getText().toString();
if (condition.equals("")) {
lv.setAdapter(adapter);
}
DBHelper helper = new DBHelper(
AddressPhoneBookDemoActivity.this);
// DBHelper 中的getUsers 函数实现查找功能
list = helper.getUsers(condition, privacy);
// 为自己查找的数据设置一个新的适配器
SimpleAdapter searchAdapter = new SimpleAdapter(
AddressPhoneBookDemoActivity.this, list,
R.layout.listitem, new String[] { "imageid",
"name", "mobilephone" }, new int[] {
R.id.user_image, R.id.tv_name,
R.id.tv_mobilephone });
// 将整合好的adapter交给listview,显示给用户看
lv.setAdapter(searchAdapter);
if (list.size() == 0) {
// 如果没有联系人的时候设置背景为没有数据的图片
Drawable nodata_bg = getResources().getDrawable(
R.drawable.nodata_bg);
mainLinearLayout.setBackgroundDrawable(nodata_bg);
setTitle("没有查到任何数据");
} else {
setTitle("共查到 " + list.size() + " 条记录");
// /如果查到后设置背景颜色为空
mainLinearLayout.setBackgroundDrawable(null);
}
return false;
}
});
}
}
/*******
* 一个简单的适配器映射到视图中定义的静态数据的XML文件 。您可以指定数据支持列表作为一个ArrayList的地图。
* ArrayList中的每个条目对应于一个排在列表中。 这个地图包含为每一行的数据。您还可以指定一个XML文件,
* 该文件定义视图用于显示的行,和一个映射键映射到特定的视图。 数据绑定到视图出现在两个阶段
*
* *
**/
private SimpleAdapter getMenuAdapter(String[] menuNameArray,
int[] imageResourceArray) {
ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < menuNameArray.length; i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("itemImage", imageResourceArray[i]);
map.put("itemText", menuNameArray[i]);
data.add(map);
}
SimpleAdapter simperAdapter = new SimpleAdapter(this, data,
R.layout.item_menu, new String[] { "itemImage", "itemText" },
new int[] { R.id.item_image, R.id.item_text });
return simperAdapter;
}
/*******
* 当退出的时候,回收资源
*
****/
protected void onDestroy() {
if (confirmDialog != null) {
confirmDialog = null;
}
if (mainMenuDialog != null) {
mainMenuDialog = null;
}
if (searchLinearout != null) {
searchLinearout = null;
}
if (mainMenuView != null) {
mainMenuView = null;
}
if (mainMenuGrid != null) {
mainMenuGrid = null;
}
if (bottomMenuGrid != null) {
bottomMenuGrid = null;
}
if (adapter != null) {
adapter = null;
}
if (list != null) {
list = null;
}
if (lv != null) {
lv = null;
}
if (DBHelper.dbInstance != null) {
DBHelper.dbInstance.close();
DBHelper.dbInstance = null;
}
System.out.println("destory!!!");
super.onDestroy();
}
}
13.接着是添加联系人的活动界面AddNewContacts.java
package com.wang.Activity;
import com.wang.Db.DBHelper;
import com.wang.UserInfo.UserInfo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView.ScaleType;
import android.widget.ViewSwitcher.ViewFactory;
public class AddNewContacts extends Activity implements ViewFactory {
EditText et_name;
EditText et_mobilePhone;
EditText et_officePhone;
EditText et_familyPhone;
EditText et_position;
EditText et_company;
EditText et_address;
EditText et_zipCode;
EditText et_otherContact;
EditText et_email;
EditText et_remark;
Button btn_save;
Button btn_return;
int privacy;
// 头像按钮
ImageButton imageButton;
// 图像选择的视图
View imageChooseView;
// 头像选择对话框
AlertDialog imageChooseDialog;
// 头像的Gallery
Gallery gallery;
// 头像的ImageSwitcher
ImageSwitcher is;
// 用于记录当前选中图像在图像数组中的位置
int currentImagePosition;
// 用于记录上一次图片的位置
int previousImagePosition;
// 判断头像有没有变化
boolean imageChanged;
/******
* 所有的图像图片
*
****/
private int[] images = new int[] { R.drawable.icon, R.drawable.image1,
R.drawable.image2, R.drawable.image3, R.drawable.image4,
R.drawable.image5, R.drawable.image6, R.drawable.image7,
R.drawable.image8, R.drawable.image9, R.drawable.image10 };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addnewcontacts);
Intent intent = getIntent();
// 先确定好保密类型
if (intent.getExtras() != null
&& intent.getExtras().getInt("privacy") == 1) {
privacy = 1;
} else {
privacy = 0;
}
// 实例化组件
et_name = (EditText) findViewById(R.id.username);
et_mobilePhone = (EditText) findViewById(R.id.mobilephone);
et_officePhone = (EditText) findViewById(R.id.officephone);
et_familyPhone = (EditText) findViewById(R.id.familyphone);
et_position = (EditText) findViewById(R.id.position);
et_company = (EditText) findViewById(R.id.company);
et_address = (EditText) findViewById(R.id.address);
et_zipCode = (EditText) findViewById(R.id.zipcode);
et_otherContact = (EditText) findViewById(R.id.othercontact);
et_email = (EditText) findViewById(R.id.email);
et_remark = (EditText) findViewById(R.id.remark);
btn_save = (Button) findViewById(R.id.save);
btn_return = (Button) findViewById(R.id.btn_return);
imageButton = (ImageButton) findViewById(R.id.image_button);
/*****
* 保存按钮的监听事件
*/
btn_save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 判断姓名是否为空
String name = et_name.getText().toString();
if (name.trim().equals("")) {
Toast.makeText(AddNewContacts.this, "姓名不许为空",
Toast.LENGTH_LONG).show();
return;
}
// 从表单上获取数据
UserInfo user = new UserInfo();
user.username = name;
user.address = et_address.getText().toString();
user.company = et_company.getText().toString();
user.email = et_email.getText().toString();
user.familyPhone = et_familyPhone.getText().toString();
user.mobilePhone = et_mobilePhone.getText().toString();
user.officePhone = et_officePhone.getText().toString();
user.otherContact = et_otherContact.getText().toString();
user.position = et_position.getText().toString();
user.remark = et_remark.getText().toString();
user.zipCode = et_zipCode.getText().toString();
// 判断头像是否改变,若改变,则用当前的位置,若没有改变,则用前一回的位置
if (imageChanged) {
user.imageId = images[currentImagePosition % images.length];
} else {
user.imageId = images[previousImagePosition % images.length];
}
user.privacy = privacy;
// 创建数据库帮助类
DBHelper helper = new DBHelper(AddNewContacts.this);
// 打开数据库
helper.openDatabase();
// 把user存储到数据库里
long result = helper.insert(user);
// 通过结果来判断是否插入成功,若为1,则表示插入数据失败
if (result == -1) {
Toast.makeText(AddNewContacts.this, "添加失败",
Toast.LENGTH_LONG);
}
setTitle("用户添加成功!");
// 返回到上一个Activity,也就是Main.activity
setResult(3);
// 销毁当前视图
finish();
}
});
/**
*
* f返回按钮的监听事件
* **/
btn_return.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
/***
* 图片按钮 的监听事件
*
* **/
imageButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 为gallery装载图片 调用下面的loadImage的方法
loadImage();
// 初始化imageChooseDialog
initImageChooseDialog();
imageChooseDialog.show();
}
});
}
/*****
* 图片按钮的装载方法实现选择图片的功能
*
* **/
public void loadImage() {
if (imageChooseView == null) {
LayoutInflater li = LayoutInflater.from(AddNewContacts.this);
imageChooseView = li.inflate(R.layout.imageswitch, null);
// 通过渲染xml文件,得到一个视图(View),再拿到这个View里面的Gallery
gallery = (Gallery) imageChooseView.findViewById(R.id.gallery);
// 为Gallery装载图片
gallery.setAdapter(new ImageAdapter(this));
// 设置选择的位置为图片的中间位置
gallery.setSelection(images.length / 2);
is = (ImageSwitcher) imageChooseView.findViewById(R.id.imageswitch);
is.setFactory(this);
// 设置动画效果淡入淡出
is.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
// 卸载图片的动画效果
is.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
// 为画廊图片设置监听事件
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// 当前的头像位置为选中的位置
currentImagePosition = arg2;
// 为ImageSwitcher设置图像
is.setImageResource(images[arg2 % images.length]);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
/**
* 自定义Gallery的适配器
*
***/
class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
/**
* gallery从这个方法中拿到image
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv = new ImageView(context);
iv.setImageResource(images[position % images.length]);
iv.setAdjustViewBounds(true);
iv.setLayoutParams(new Gallery.LayoutParams(80, 80));
iv.setPadding(15, 10, 15, 10);
return iv;
}
}
@Override
public View makeView() {
ImageView view = new ImageView(this);
view.setBackgroundColor(0xff000000);
// 控制图像应调整大小和移动以匹配这个ImageView的大小 居中
view.setScaleType(ScaleType.FIT_CENTER);
// 设置图片的大小为 90 * 90
view.setLayoutParams(new ImageSwitcher.LayoutParams(90, 90));
return view;
}
public void initImageChooseDialog() {
if (imageChooseDialog == null) {
// 选择图片的对话框
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("请选择图像")
.setView(imageChooseView).setPositiveButton("确定",
new DialogInterface.OnClickListener() {
// 确定按钮的监听事件
public void onClick(DialogInterface dialog, int which) {
imageChanged = true;
previousImagePosition = currentImagePosition;
// 设置图片为选择图片的通过位置
imageButton
.setImageResource(images[currentImagePosition
% images.length]);
}
}).setNegativeButton("取消",
new DialogInterface.OnClickListener() {
// 取消按钮的监听事件
@Override
public void onClick(DialogInterface dialog, int which) {
currentImagePosition = previousImagePosition;
}
});
imageChooseDialog = builder.create();
}
}
/**
* 当退出的时候,回收资源
*/
@Override
protected void onDestroy() {
if (is != null) {
is = null;
}
if (gallery != null) {
gallery = null;
}
if (imageChooseDialog != null) {
imageChooseDialog = null;
}
if (imageChooseView != null) {
imageChooseView = null;
}
if (imageButton != null) {
imageButton = null;
}
super.onDestroy();
}
}
package com.wang.Db;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import com.wang.UserInfo.UserInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
public class DBHelper {
public static final String DB_DBNAME = "Addressphone";
public static final String DB_TABLENAME = "addressphone";
public static final int VERSION = 4;
public static SQLiteDatabase dbInstance;
private MyDBHelper myDBHelper;
private StringBuffer tableCreate;
private Context context;
public DBHelper(Context context) {
this.context = context;
}
// 打开数据库
public void openDatabase() {
if (dbInstance == null) {
myDBHelper = new MyDBHelper(context, DB_DBNAME, VERSION);
dbInstance = myDBHelper.getWritableDatabase();
}
}
/**
* 往数据库里面的user表插入一条数据,若失败返回-1
*/
public long insert(UserInfo user) {
ContentValues values = new ContentValues();
values.put("name", user.username);
values.put("mobilephone", user.mobilePhone);
values.put("officephone", user.officePhone);
values.put("familyphone", user.familyPhone);
values.put("address", user.address);
values.put("othercontact", user.otherContact);
values.put("email", user.email);
values.put("position", user.position);
values.put("company", user.company);
values.put("zipcode", user.zipCode);
values.put("remark", user.remark);
values.put("imageid", user.imageId);
values.put("privacy", user.privacy);
return dbInstance.insert(DB_TABLENAME, null, values);
}
/**
* 获得数据库中所有的用户,将每一个用户放到一个map中去,然后再将map放到list里面去返回
*/
public ArrayList getAllUser(boolean privacy) {
ArrayList list = new ArrayList();
Cursor cursor = null;
if (privacy) {
cursor = dbInstance.query(DB_TABLENAME, new String[] { "_id",
"name", "mobilephone", "officephone", "familyphone",
"address", "othercontact", "email", "position", "company",
"zipcode", "remark", "imageid" },
"privacy=1", null, null, null, null);
} else {
cursor = dbInstance.query(DB_TABLENAME, new String[] { "_id",
"name", "mobilephone", "officephone", "familyphone",
"address", "othercontact", "email", "position", "company",
"zipcode", "remark", "imageid" }, "privacy=0", null, null,
null, null);
}
while (cursor.moveToNext()) {
HashMap item = new HashMap();
item.put("_id", cursor.getInt(cursor.getColumnIndex("_id")));
item.put("name", cursor.getString(cursor.getColumnIndex("name")));
item.put("mobilephone", cursor.getString(cursor
.getColumnIndex("mobilephone")));
item.put("officephone", cursor.getString(cursor
.getColumnIndex("officephone")));
item.put("familyphone", cursor.getString(cursor
.getColumnIndex("familyphone")));
item.put("address", cursor.getString(cursor
.getColumnIndex("address")));
item.put("othercontact", cursor.getString(cursor
.getColumnIndex("othercontact")));
item.put("email", cursor.getString(cursor.getColumnIndex("email")));
item.put("position", cursor.getString(cursor
.getColumnIndex("position")));
item.put("company", cursor.getString(cursor
.getColumnIndex("company")));
item.put("zipcode", cursor.getString(cursor
.getColumnIndex("zipcode")));
item.put("remark", cursor
.getString(cursor.getColumnIndex("remark")));
item
.put("imageid", cursor.getInt(cursor
.getColumnIndex("imageid")));
list.add(item);
}
return list;
}
/**
* 删除数据库表中的某条信息
* **/
public void delete(int _id) {
dbInstance.delete(DB_TABLENAME, "_id=?", new String[] { String
.valueOf(_id) });
}
/**
* 删除数据库表中的所有信息
* **/
public void deleteAll(int privacy) {
dbInstance.delete(DB_TABLENAME, "privacy=?", new String[] { String
.valueOf(privacy) });
}
/**
* 得到数据库表中的总的条目数
* **/
public int getTotalCount() {
Cursor cursor = dbInstance.query(DB_TABLENAME,
new String[] { "count(*)" }, null, null, null, null, null);
cursor.moveToNext();
return cursor.getInt(0);
}
/**
* 得到联系人的信息
* **/
//
public ArrayList getUsers(String condition, boolean privacy) {
ArrayList list = new ArrayList();
String strSelection = "";
if (privacy) {
strSelection = "and privacy = 1";
} else {
strSelection = "and privacy = 0";
}
// 模糊查询
String sql = "select * from " + DB_TABLENAME
+ " where 1=1 and (name like '%" + condition + "%' "
+ "or mobilephone like '%" + condition
+ "%' or familyphone like '%" + condition + "%' "
+ "or officephone like '%" + condition + "%')" + strSelection;
Cursor cursor = dbInstance.rawQuery(sql, null);
while (cursor.moveToNext()) {
HashMap item = new HashMap();
item.put("_id", cursor.getInt(cursor.getColumnIndex("_id")));
item.put("name", cursor.getString(cursor.getColumnIndex("name")));
item.put("mobilephone", cursor.getString(cursor
.getColumnIndex("mobilephone")));
item.put("officephone", cursor.getString(cursor
.getColumnIndex("officephone")));
item.put("familyphone", cursor.getString(cursor
.getColumnIndex("familyphone")));
item.put("address", cursor.getString(cursor
.getColumnIndex("address")));
item.put("othercontact", cursor.getString(cursor
.getColumnIndex("othercontact")));
item.put("email", cursor.getString(cursor.getColumnIndex("email")));
item.put("position", cursor.getString(cursor
.getColumnIndex("position")));
item.put("company", cursor.getString(cursor
.getColumnIndex("company")));
item.put("zipcode", cursor.getString(cursor
.getColumnIndex("zipcode")));
item.put("remark", cursor
.getString(cursor.getColumnIndex("remark")));
item
.put("imageid", cursor.getInt(cursor
.getColumnIndex("imageid")));
list.add(item);
}
return list;
}
/**
* 删除标记
* **/
public void deleteMarked(ArrayList<Integer> deleteId) {
StringBuffer strDeleteId = new StringBuffer();
strDeleteId.append("_id=");
for (int i = 0; i < deleteId.size(); i++) {
if (i != deleteId.size() - 1) {
strDeleteId.append(deleteId.get(i) + " or _id=");
} else {
strDeleteId.append(deleteId.get(i));
}
}
dbInstance.delete(DB_TABLENAME, strDeleteId.toString(), null);
System.out.println(strDeleteId.toString());
}
/**
* 备份数据
* **/
//
public void backupData(boolean privacy) {
StringBuffer sqlBackup = new StringBuffer();
Cursor cursor = null;
if (privacy) {
cursor = dbInstance.query(DB_TABLENAME, new String[] { "_id",
"name", "mobilephone", "officephone", "familyphone",
"address", "othercontact", "email", "position", "company",
"zipcode", "remark", "imageid,privacy" }, "privacy=1",
null, null, null, null);
} else {
cursor = dbInstance.query(DB_TABLENAME, new String[] { "_id",
"name", "mobilephone", "officephone", "familyphone",
"address", "othercontact", "email", "position", "company",
"zipcode", "remark", "imageid,privacy" }, "privacy=0",
null, null, null, null);
}
while (cursor.moveToNext()) {
sqlBackup
.append(
"insert into "
+ DB_TABLENAME
+ "(name,mobilephone,officephone,familyphone,address,othercontact,email,position,company,zipcode,remark,imageid,privacy)")
.append(" values ('")
.append(cursor.getString(cursor.getColumnIndex("name")))
.append("','")
.append(
cursor.getString(cursor
.getColumnIndex("mobilephone")))
.append("','")
.append(
cursor.getString(cursor
.getColumnIndex("officephone")))
.append("','")
.append(
cursor.getString(cursor
.getColumnIndex("familyphone")))
.append("','")
.append(cursor.getString(cursor.getColumnIndex("address")))
.append("','")
.append(
cursor.getString(cursor
.getColumnIndex("othercontact")))
.append("','")
.append(cursor.getString(cursor.getColumnIndex("email")))
.append("','")
.append(cursor.getString(cursor.getColumnIndex("position")))
.append("','").append(
cursor.getString(cursor.getColumnIndex("company")))
.append("','").append(
cursor.getString(cursor.getColumnIndex("zipcode")))
.append("','").append(
cursor.getString(cursor.getColumnIndex("remark")))
.append("',").append(
cursor.getInt(cursor.getColumnIndex("imageid")))
.append(",").append(
cursor.getInt(cursor.getColumnIndex("privacy")))
.append(");").append("\n");
}
saveDataToFile(sqlBackup.toString(), privacy);
}
/**
* 保存数据到文件中
* **/
private void saveDataToFile(String strData, boolean privacy) {
String fileName = "";
if (privacy) {
fileName = "priv_data.bk";
} else {
fileName = "comm_data.bk";
}
try {
String SDPATH = Environment.getExternalStorageDirectory() + "/";
File fileParentPath = new File(SDPATH + "zpContactData/");
fileParentPath.mkdirs();
File file = new File(SDPATH + "zpContactData/" + fileName);
System.out.println("the file previous path = "
+ file.getAbsolutePath());
file.createNewFile();
System.out
.println("the file next path = " + file.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(file);
fos.write(strData.getBytes());
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 恢复备份数据方法
* **/
//
public void restoreData(String fileName) {
try {
String SDPATH = Environment.getExternalStorageDirectory() + "/";
File file = null;
if (fileName.endsWith(".bk")) {
file = new File(SDPATH + "zpContactData/" + fileName);
} else {
file = new File(SDPATH + "zpContactData/" + fileName + ".bk");
}
BufferedReader br = new BufferedReader(new FileReader(file));
String str = "";
while ((str = br.readLine()) != null) {
System.out.println(str);
dbInstance.execSQL(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 查找备份的文件
* **/
public boolean findFile(String fileName) {
String SDPATH = Environment.getExternalStorageDirectory() + "/";
File file = null;
if (fileName.endsWith(".bk")) {
file = new File(SDPATH + "zpContact/" + fileName);
} else {
file = new File(SDPATH + "zpContact/" + fileName + ".bk");
}
if (file.exists()) {
return true;
} else {
return false;
}
}
/**
* 创建一个打开数据库的方法
* **/
class MyDBHelper extends SQLiteOpenHelper {
public MyDBHelper(Context context, String name, int version) {
super(context, name, null, version);
}
// 创建数据库
public void onCreate(SQLiteDatabase db) {
tableCreate = new StringBuffer();
// 创建表
tableCreate.append("create table ").append(DB_TABLENAME).append(
" (").append("_id integer primary key autoincrement,")
.append("name text,").append("mobilephone text,").append(
"officephone text,").append("familyphone text,")
.append("address text,").append("othercontact text,")
.append("email text,").append("position text,").append(
"company text,").append("zipcode text,").append(
"remark text,").append("imageid int,").append(
"privacy int ").append(")");
System.out.println(tableCreate.toString());
// 执行创建语句
db.execSQL(tableCreate.toString());
}
// 数据库时需要升级删除表,在重新创建
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "drop table if exists " + DB_TABLENAME;
db.execSQL(sql);
myDBHelper.onCreate(db);
}
}
}
15.然后呢,就是用户信息的类UserInfo.java
package com.wang.UserInfo;
import java.io.Serializable;
public class UserInfo implements Serializable{
public int _id;
public String username;
public String mobilePhone;
public String officePhone;
public String familyPhone;
public String position;
public String company;
public String address;
public String zipCode;
public String email;
public String otherContact;
public String remark;
public int imageId;
public int privacy;//1代表隐私用户 0代表普通用户
}
16.亲,最后别忘了添加权限和注册Activity哦!!
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wang.Activity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".startAnimation"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".AddressPhoneBookDemoActivity" />
<activity android:name=".AddNewContacts" />
</application>
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
17.然后就可以看到运行结果喽!!运行结果如下:
解释一下,第一张的欢迎界面, 第二张是跳转的的主界面 第三张的点击item拨打联系人电话的界面
第四张的增加联系人的界面 第五张的选择联系人头像的界面 第六张是查找联系人的界面
第七张是删除一条已标记的联系人的界面 第八张是管理联系人的界面 第九张的删除所有联系人的界面
第十张是调用系统拨号功能的界面 第十一张是备份数据的界面 第十二章是备份完成的界面
下载地址:点击打开链接
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!