代码下载地址
点击打开链接
自己之前写过几个联系人索引条的小demo,但没有在项目中自己体验过,最近项目中有用到,这个功能模块是同事写的,今天抽空摘出来下,以保存,将来可以用到
接下来就一步步简单的说下思路吧:action开始
首先先看下主界面的布局文件吧
<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:background="@color/bg2">
<RelativeLayout
android:id="@+id/re_head"
android:layout_width="fill_parent"
android:layout_height="48dp"
android:background="@color/bg1">
<ImageView
android:id="@+id/image_back"
android:layout_width="44dp"
android:layout_height="fill_parent"
android:src="@drawable/selector_top_return"
android:paddingLeft="10dp"
android:paddingRight="10dp"/>
<RelativeLayout
android:id="@+id/rl_import_search"
android:layout_width="250dp"
android:layout_height="32dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@id/image_back">
<EditText
android:id="@+id/et_common_search_text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerVertical="true"
android:background="@drawable/rounded_search_text"
android:paddingLeft="30dp"
android:scaleType="centerCrop"
android:text="" >
</EditText>
<ImageView
android:id="@+id/iv_common_search"
android:layout_width="14dp"
android:layout_height="14dp"
android:layout_alignLeft="@+id/et_common_search_text"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:background="@drawable/image_search"
android:visibility="visible" />
</RelativeLayout>
<CheckBox
android:button="@null"
android:id="@+id/cb_select_all"
android:text="全选"
android:layout_width="48dp"
android:layout_height="fill_parent"
android:textSize="16sp"
android:layout_alignParentRight="true"
android:gravity="center_vertical"
android:textColor="#ffffff"/>
</RelativeLayout>
<View
android:id="@+id/view_extra"
android:background="#e6e6e6"
android:layout_below="@id/re_head"
android:layout_width="match_parent"
android:layout_height="10dp" />
<ListView
android:id="@+id/lv_contact_list"
android:layout_width="340dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="@id/view_extra"
android:layout_marginBottom="49dp"
android:cacheColorHint="#000000"
android:descendantFocusability="afterDescendants"
android:fadingEdge="none"
android:visibility="visible" />
<com.example.contactdemo.QuickAlphabeticBar
android:id="@+id/qab_contact_list_fast_scroller"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignTop="@id/lv_contact_list"
android:layout_marginBottom="90dp"
android:layout_marginTop="30dp"
android:background="#f8f8f8"
android:scaleType="centerInside" >
</com.example.contactdemo.QuickAlphabeticBar>
<TextView
android:id="@+id/tv_contact_list_fast_position"
android:layout_width="70dip"
android:layout_height="70dip"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal|top"
android:layout_margin="34dip"
android:gravity="center"
android:padding="2dip"
android:textColor="#404040"
android:textSize="48dip"
android:typeface="sans"
android:visibility="invisible" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="51dp"
android:layout_alignParentBottom="true"
android:orientation="vertical">
<View
android:id="@+id/view_1"
android:background="#cacaca"
android:layout_width="match_parent"
android:layout_height="1dp" />
<LinearLayout
android:id="@+id/ll_buttom"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/bg3"
android:orientation="horizontal" >
<TextView
android:id="@+id/tv_cancel"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:text="取消"
android:layout_weight="1"
android:gravity="center"
android:textSize="16sp"
android:textColor="@color/b4"/>
<TextView
android:id="@+id/tv_sure"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="确定"
android:gravity="center"
android:textSize="16sp"
android:textColor="@color/h1"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="340dp"
android:layout_height="match_parent"
android:background="@color/bg2"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/relative_contact_list_item_alpha"
android:layout_width="340dp"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="@+id/ll_contact_list_item_alpha"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:background="@color/bg2" >
<TextView
android:id="@+id/tv_contact_list_item_alpha"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:text="111"
android:textColor="@color/b3"
android:textSize="@dimen/textSize_s2"
android:typeface="sans" />
</RelativeLayout>
<View
android:id="@+id/view_line"
android:layout_width="287dp"
android:layout_height="1px"
android:layout_alignParentRight="true"
android:background="@drawable/line"
android:visibility="gone" />
</RelativeLayout>
<RelativeLayout
android:layout_width="340dp"
android:layout_height="60dp"
android:layout_marginRight="20dp"
android:background="@color/bg3" >
<!-- 联系人信息 -->
<CheckBox
android:id="@+id/cb_check"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:layout_marginLeft="17dp"
android:button="@drawable/selector_check"
android:focusableInTouchMode="false" />
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@id/cb_check"
android:text="xxx"
android:textColor="@color/b1"
android:textSize="@dimen/textSize_s2" />
</RelativeLayout>
</LinearLayout>以上的主界面布局文件和item布局文件已经弄好了,接下来就看下主界面代码,然后在稍微做下说明
ImportContactActivity
package com.example.contactdemo;
import java.util.ArrayList;
import java.util.Collections;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ImportContactActivity extends Activity {
private static final String LOG_TAG = ImportContactActivity.class.getSimpleName();
private EditText editSearch;
private CheckBox selectAll;
private ListView lvContacts;
private TextView tvCancel;
private TextView tvSure;
private QuickAlphabeticBar alphabeticBar;
private ArrayList<ContactMember> listsContact;
private ArrayList<ContactMember> importListContact;
private ArrayList<ContactMember> filterListsContact = new ArrayList<ContactMember>();
private ContactsListAdapter contactsListAdapter;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_import_contact);
/**初始化布局控件资源*/
initView();
/**数据源*/
listsContact = ContactsManager.getInstance().getContacts();
Log.i(LOG_TAG, "size=" + listsContact.size());
/**测试log信息*/
for (int i = 0; i < listsContact.size(); i++) {
ContactMember member = listsContact.get(i);
Log.i(LOG_TAG, "name=" + member.getContactName() + ",number=" + member.getContactPhones().get(0) + ",sortKey=" + member.getSortKey() + ",id=" + member.getContactId());
}
/**
* 全选操作
*/
selectAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selectAll.isChecked()) {
contactsListAdapter.initSelectedState(true);
contactsListAdapter.notifyDataSetChanged();
} else {
contactsListAdapter.initSelectedState(false);
contactsListAdapter.notifyDataSetChanged();
}
}
});
/**
* 过滤联系人
*/
editSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
filterContacts(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});
/**
* 取消过滤
*/
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
contactsListAdapter.initSelectedState(false);
contactsListAdapter.notifyDataSetChanged();
}
});
/**
* 确定过滤
*/
tvSure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
count=0;
final ImportingDialog importingDialog = new ImportingDialog(ImportContactActivity.this);
importListContact = contactsListAdapter.getListsContact(); //需要判断一下importListContact中isCheck
for (ContactMember member : importListContact) {
if (member.isCheck()) {
count++;
}
}
if (count > 0) {
importingDialog.show();
new AsyncTask<Void, Integer, Void>() {
@Override
protected Void doInBackground(Void... params) {
int importCount = 0;
for (ContactMember member : importListContact) {
if (member.isCheck()) {
importCount++;
Log.i(LOG_TAG, "name = " + member.getContactName());
//add by wyf
VChatSipInfoStorage.getInstance().insertStuAllColumn(member);
publishProgress(importCount);
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
importingDialog.notifyByteProgress(count, values[0]);
}
@Override
protected void onPostExecute(Void aVoid) {
importingDialog.onComplete();
}
}.execute();
} else {
Toast.makeText(ImportContactActivity.this, "未选中任何联系人", Toast.LENGTH_SHORT).show();
}
}
});
/**适配器*/
contactsListAdapter = new ContactsListAdapter(this, listsContact, alphabeticBar);
lvContacts.setAdapter(contactsListAdapter);
lvContacts.setDividerHeight(0);
/**设置字母条的一些初始化信息*/
alphabeticBar.init(this);
alphabeticBar.setListView(lvContacts);
alphabeticBar.setVisibility(View.VISIBLE);
}
/*
* 获取布局控件资源
*/
private void initView() {
editSearch = (EditText) findViewById(R.id.et_common_search_text);
selectAll = (CheckBox) findViewById(R.id.cb_select_all);
lvContacts = (ListView) findViewById(R.id.lv_contact_list);
tvCancel = (TextView) findViewById(R.id.tv_cancel);
tvSure = (TextView) findViewById(R.id.tv_sure);
alphabeticBar = (QuickAlphabeticBar) findViewById(R.id.qab_contact_list_fast_scroller);
}
public TextView getTvSure() {
return tvSure;
}
private void filterContacts(String filter) {
Log.i("TAG", "filter=" + filter);
filterListsContact.clear();
if (TextUtil.isEmpty(filter)) {
filterListsContact.addAll(listsContact);
} else {
for (ContactMember member : listsContact) {
if (isChinese(member.getContactName().charAt(0))) {//联系人的首为中文
if (isChinese(filter.charAt(0))) {//如果输入中文搜索
if (member.getContactName().startsWith(filter))
filterListsContact.add(member);
} else {//如果输入英文搜索
if (isNameAndFilterEqual(CharacterParser.getInstance().getSelling(member.getContactName()), filter))
filterListsContact.add(member);
}
} else {
if (isNameAndFilterEqual(member.getContactName(), filter))
filterListsContact.add(member);
}
}
}
Collections.sort(filterListsContact, new Pycomparator());
contactsListAdapter.updateListView(filterListsContact);
}
private boolean isChinese(char a) {
return String.valueOf(a).matches("[\u4E00-\u9FA5]");
}
private boolean isNameAndFilterEqual(String name, String filter) {
for (int i = 0; i < filter.length(); i++) {
if (!(name.charAt(i) == filter.charAt(i) || convertLowerAndUpper(name.charAt(i)) == filter.charAt(i)))
return false;
}
return true;
}
private char convertLowerAndUpper(char ch) {
if (ch >= 'a' && ch <= 'z')
return String.valueOf(ch).toUpperCase().charAt(0);
else
return String.valueOf(ch).toLowerCase().charAt(0);
}
}
package com.example.contactdemo;
import java.util.ArrayList;
import java.util.Collections;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
/**
* Created by wyf on 2016/4/13.
*/
public class ContactsManager {
private static ContactsManager instance;
public static ContactsManager getInstance(){
if (instance==null){
instance=new ContactsManager();
}
return instance;
}
//获取联系人的信息并排序
public ArrayList<ContactMember> getContacts(){
long oldContactId=-1;
ArrayList<String> contactPhones=new ArrayList<String>();
ContactMember member=null;
ArrayList<ContactMember> listsContacts=new ArrayList<ContactMember>();
Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor cursor;
String[] projection={ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER};
cursor= MyApplication.getInstance().getContentResolver().query(uri,projection,null,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
System.out.println("cursor="+cursor);
if (cursor!=null&&cursor.getCount()>0){
while (cursor.moveToNext()){
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String oldSortKey=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY));
String newSortKey=oldSortKey;
if (isChinese(oldSortKey.charAt(0))){
newSortKey=CharacterParser.getInstance().getSelling(oldSortKey);
}
String sortKey=getSortKey(newSortKey);
long contactId=cursor.getLong(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String number=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactId==oldContactId){
contactPhones.add(number);
member.setContactPhones(contactPhones);
continue;
}else{
member=new ContactMember();
listsContacts.add(member);
contactPhones=new ArrayList<String>();
contactPhones.add(number);
}
member.setSortKey(sortKey);
member.setContactPhones(contactPhones);
member.setContactName(name);
member.setContactId(contactId);
oldContactId=contactId;
}
}
if (listsContacts!=null)
Collections.sort(listsContacts,new Pycomparator());
return listsContacts;
}
private String getSortKey(String sortKey){
String key=sortKey.substring(0,1).toUpperCase();
if (key.matches("[A-Z]")){
return key;
}
return "#";
}
private boolean isChinese(char a){
return String.valueOf(a).matches("[\u4E00-\u9FA5]");
}
}
Pycomparator
package com.example.contactdemo;
import java.util.ArrayList;
import java.util.Comparator;
/**
* Created by Administrator on 2016/4/14.
*/
public class Pycomparator implements Comparator<ContactMember> {
@Override
public int compare(ContactMember contact1, ContactMember contact2) {
String name1=contact1.getSortKey();
String name2=contact2.getSortKey();
if (TextUtil.isEmpty(name1)){
ArrayList<String> contactPhones=contact1.getContactPhones();
if (contactPhones!=null&&contactPhones.size()>0)
name1=contactPhones.get(0);
}
if (TextUtil.isEmpty(name2)){
ArrayList<String> contactPhones=contact2.getContactPhones();
if (contactPhones!=null&&contactPhones.size()>0){
name2=contactPhones.get(0);
}
}
if (!TextUtil.isEmpty(name1)&&!TextUtil.isEmpty(name2)){
boolean firstisChar=false;
boolean secondisChar=false;
if (((name1.charAt(0)>='a'&&name1.charAt(0)<='z'))||(name1.charAt(0)>='A'&&name1.charAt(0)<='Z'))
firstisChar=true;
if (((name2.charAt(0)>='a'&&name2.charAt(0)<='z'))||(name2.charAt(0)>='A'&&name2.charAt(0)<='Z'))
secondisChar=true;
if (firstisChar&&secondisChar){
return name1.compareToIgnoreCase(name2);
}else if (firstisChar&&!secondisChar){
return -1;
}else if (!firstisChar&&secondisChar){
return 1;
}else{
return name1.compareToIgnoreCase(name2);
}
}
return 0;
}
}
数据源有了接下来看下适配器里面的内容
ContactsListAdapter
package com.example.contactdemo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Created by Administrator on 2016/4/13.
*/
public class ContactsListAdapter extends BaseAdapter{
private static String LOG_TAG=ContactsListAdapter.class.getSimpleName();
private LayoutInflater inflater;
private Context context;
private ArrayList<ContactMember> listsContact;
private HashMap<String,Integer> alphaIndexer;//字母表的对应
private HashMap<Long,Boolean> isSelected;//用来控制CheckBox的选中情况
private String[] sections;
public ContactsListAdapter(Context context,ArrayList<ContactMember> listsContact,QuickAlphabeticBar alphabet){
initContactListsAdapter(context,listsContact,alphabet);
}
public ContactsListAdapter(Context context,ArrayList<ContactMember> listsContact,QuickAlphabeticBar alphabet,boolean isMultiChoice){
initContactListsAdapter(context,listsContact,alphabet);
}
private void initContactListsAdapter(Context context,ArrayList<ContactMember> listsContact,QuickAlphabeticBar alphabet){
this.context=context;
this.listsContact=listsContact;
this.inflater=LayoutInflater.from(context);
this.alphaIndexer=new HashMap<String,Integer>();
initAlphabeticBar(alphabet);
isSelected=new HashMap<Long,Boolean>();
initSelectedState(false);
}
public void initAlphabeticBar(QuickAlphabeticBar alpha){
alphaIndexer=new HashMap<String,Integer>();
for (int i=0;i<listsContact.size();i++){
String sortKey=listsContact.get(i).getSortKey();
if (!alphaIndexer.containsKey(sortKey)){
System.out.println("sortKey==="+sortKey);
alphaIndexer.put(sortKey,i);
}
}
Set<String> sectionLetter=alphaIndexer.keySet();
ArrayList<String> sectionList=new ArrayList<String>(sectionLetter);
Collections.sort(sectionList);
sections=new String[sectionList.size()];
sectionList.toArray(sections);
alpha.setEnabled(false);
alpha.setAlphaIndexer(alphaIndexer);
}
public void initSelectedState(boolean isSelectedAll){
isSelected.clear();
if (isSelectedAll){
for (int i=0;i<listsContact.size();i++){
isSelected.put(listsContact.get(i).getContactId(),true);
listsContact.get(i).setIsCheck(true);
}
}else{
for (int i=0;i<listsContact.size();i++){
isSelected.put(listsContact.get(i).getContactId(),false);
listsContact.get(i).setIsCheck(false);
}
}
}
public void updateListView(ArrayList<ContactMember> listsContact){
this.listsContact=listsContact;
notifyDataSetChanged();
}
public HashMap<Long, Boolean> getIsSelected() {
return isSelected;
}
@Override
public int getCount() {
return listsContact.size();
}
@Override
public Object getItem(int position) {
return listsContact.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
System.out.println("position=="+position);
final ViewHolder viewHolder;
if (convertView==null){
convertView=inflater.inflate(R.layout.contact_list_item,parent,false);
viewHolder=new ViewHolder(convertView);
convertView.setTag(viewHolder);
}else{
viewHolder= (ViewHolder) convertView.getTag();
}
if (listsContact.size()<1){
return null;
}
final ContactMember contact=listsContact.get(position);
String name=contact.getContactName();
String number=null;
final ArrayList<String> contactPhones=contact.getContactPhones();
for (int i=0;i<contactPhones.size();i++){
if (contactPhones.get(i)!=null){
number=contactPhones.get(i);
break;
}
}
if (name==null)
name=number;
viewHolder.name.setText(name);
String sortKey=contact.getSortKey();
String currentStr=sortKey;
String previewStr=position-1>=0?listsContact.get(position-1).getSortKey():"";
if (!previewStr.equals(currentStr)){
viewHolder.alpha.setVisibility(View.VISIBLE);
viewHolder.alpha.setText(currentStr);
viewHolder.ll_contact_list_item_alpha.setVisibility(View.VISIBLE);
viewHolder.viewLine.setVisibility(View.GONE);
}else{
viewHolder.alpha.setVisibility(View.GONE);
viewHolder.alpha.setText(null);
viewHolder.ll_contact_list_item_alpha.setVisibility(View.GONE);
viewHolder.viewLine.setVisibility(View.VISIBLE);
}
viewHolder.cb_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int count = 0;
System.out.println("状态发生了变化,position=" + position + ",isCheck=" + buttonView.isChecked());
isSelected.put(listsContact.get(position).getContactId(), isChecked);
listsContact.get(position).setIsCheck(getIsSelected().get(listsContact.get(position).getContactId()));
System.out.println("name=" + listsContact.get(position).getContactName() + ",isCheck=" + listsContact.get(position).isCheck());
if (isSelected.size() > 0) {
Iterator<Boolean> iterator = isSelected.values().iterator();
while (iterator.hasNext()) {
if (iterator.next() == true) {
count++;
}
}
if (count > 0) {
((ImportContactActivity) context).getTvSure().setText("确定(" + count + ")");
((ImportContactActivity) context).getTvSure().setEnabled(true);
} else {
((ImportContactActivity) context).getTvSure().setText("确定");
((ImportContactActivity) context).getTvSure().setEnabled(false);
}
} else if (isSelected.size() == 0) {
((ImportContactActivity) context).getTvSure().setText("确定");
((ImportContactActivity) context).getTvSure().setEnabled(false);
}
}
});
viewHolder.cb_check.setChecked(getIsSelected().get(listsContact.get(position).getContactId()));
listsContact.get(position).setIsCheck(getIsSelected().get(listsContact.get(position).getContactId()));
return convertView;
}
class ViewHolder{
TextView alpha;
View viewLine;
TextView name;
CheckBox cb_check;
RelativeLayout ll_contact_list_item_alpha;
public ViewHolder(View view){
alpha= (TextView) view.findViewById(R.id.tv_contact_list_item_alpha);
viewLine=view.findViewById(R.id.view_line);
name= (TextView) view.findViewById(R.id.tv_name);
cb_check= (CheckBox) view.findViewById(R.id.cb_check);
ll_contact_list_item_alpha= (RelativeLayout) view.findViewById(R.id.ll_contact_list_item_alpha);
}
}
public ArrayList<ContactMember> getListsContact() {
return listsContact; //返回列表中所有的联系人
}
}
上面代码中还用到一个工具类就是拼音转换
CharacterParser
package com.example.contactdemo;
/**
* Created by Administrator on 2016/4/14.
*/
public class CharacterParser {
private static int[] pyvalue = new int[] {-20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032,
-20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728,
-19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261,
-19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961,
-18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490,
-18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988,
-17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692,
-17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733,
-16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419,
-16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959,
-15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631,
-15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180,
-15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941,
-14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857,
-14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353,
-14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094,
-14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831,
-13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329,
-13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860,
-12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300,
-12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358,
-11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014,
-10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309,
-10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254};
public static String[] pystr = new String[] {"a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian",
"biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan", "chang", "chao", "che",
"chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", "cou", "cu", "cuan",
"cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du",
"duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga", "gai", "gan", "gang",
"gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang",
"hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian",
"jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken",
"keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng",
"li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai",
"man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai",
"nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan",
"nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu",
"qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re",
"ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha",
"shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun",
"shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao",
"tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi",
"xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi",
"yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha",
"zhai", "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui",
"zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo"};
private StringBuilder buffer;
private String resource;
private static CharacterParser characterParser = new CharacterParser();
public static CharacterParser getInstance() {
return characterParser;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
/** * 汉字转成ASCII码 * * @param chs * @return */
private int getChsAscii(String chs) {
int asc = 0;
try {
byte[] bytes = chs.getBytes("gb2312");
if (bytes == null || bytes.length > 2 || bytes.length <= 0) {
throw new RuntimeException("illegal resource string");
}
if (bytes.length == 1) {
asc = bytes[0];
}
if (bytes.length == 2) {
int hightByte = 256 + bytes[0];
int lowByte = 256 + bytes[1];
asc = (256 * hightByte + lowByte) - 256 * 256;
}
} catch (Exception e) {
System.out.println("ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);
}
return asc;
}
/** * 单字解析 * * @param str * @return */
public String convert(String str) {
String result = null;
int ascii = getChsAscii(str);
if (ascii > 0 && ascii < 160) {
result = String.valueOf((char) ascii);
} else {
for (int i = (pyvalue.length - 1); i >= 0; i--) {
if (pyvalue[i] <= ascii) {
result = pystr[i];
break;
}
}
}
return result;
}
/** * 词组解析 * * @param chs * @return */
public String getSelling(String chs) {
String key, value;
buffer = new StringBuilder();
for (int i = 0; i < chs.length(); i++) {
key = chs.substring(i, i + 1);
if (key.getBytes().length >= 2) {
value = (String) convert(key);
if (value == null) {
value = "unknown";
}
} else {
value = key;
}
buffer.append(value);
}
return buffer.toString();
}
public String getSpelling() {
return this.getSelling(this.getResource());
}
}
上面代码中 alpha.setAlphaIndexer(alphaIndexer);这个是初始化字母条的索引的字母的,接下来看下字母条里面的一些点
QuickAlphabeticBar
package com.example.contactdemo;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
/**
* 字母索引条
*
* @author Administrator
*
*/
@SuppressLint("ResourceAsColor")
public class QuickAlphabeticBar extends ImageButton {
private TextView mDialogText; // 中间显示字母的文本框
private Handler mHandler; // 处理UI的句柄
private ListView mList; // 列表
private float mHight; // 高度
// 字母列表索引
private String[] letters = new String[] { "A", "B", "C", "D", "E", "F",
"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z", "#" };
private int[] array_drawables = new int[] { R.drawable.letter_a,
R.drawable.letter_b, R.drawable.letter_c, R.drawable.letter_d,
R.drawable.letter_e, R.drawable.letter_f, R.drawable.letter_g,
R.drawable.letter_h, R.drawable.letter_i, R.drawable.letter_j,
R.drawable.letter_k, R.drawable.letter_l, R.drawable.letter_m,
R.drawable.letter_n, R.drawable.letter_o, R.drawable.letter_p,
R.drawable.letter_q, R.drawable.letter_r, R.drawable.letter_s,
R.drawable.letter_t, R.drawable.letter_u, R.drawable.letter_v,
R.drawable.letter_w, R.drawable.letter_x, R.drawable.letter_y,
R.drawable.letter_z, R.drawable.letter_end };
// 字母索引哈希表
private HashMap<String, Integer> alphaIndexer;
Paint paint = new Paint();
int choose = -1;
public QuickAlphabeticBar(Context context) {
super(context);
}
public QuickAlphabeticBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public QuickAlphabeticBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
// 初始化
public void init(Activity ctx) {
mDialogText = (TextView) ctx
.findViewById(R.id.tv_contact_list_fast_position);
if (mDialogText != null)
mDialogText.setVisibility(View.INVISIBLE);
mHandler = new Handler();
}
// 设置需要索引的列表
public void setListView(ListView mList) {
this.mList = mList;
}
public void setAlphaIndexer(HashMap<String, Integer> alphaIndexer) {
this.alphaIndexer = alphaIndexer;
postInvalidate();
}
public void setHight(float mHight) {
this.mHight = mHight;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int act = event.getAction();
float y = event.getY();
final int oldChoose = choose;
mHight = getHeight();
final int selectIndex = (int) (y / (mHight / letters.length));
System.out.println(selectIndex);
System.out.println("y=============================" + y);
if (selectIndex > -1 && selectIndex < letters.length) {// 防止越界
String key = letters[selectIndex];
if (alphaIndexer.containsKey(key)) {
int pos = alphaIndexer.get(key);
this.mList.setSelection(pos);
mDialogText.setBackgroundResource(array_drawables[selectIndex]);
invalidate();
}
}
switch (act) {
case MotionEvent.ACTION_DOWN:
if (oldChoose != selectIndex) {
if (selectIndex >= 0 && selectIndex < letters.length) {
if (alphaIndexer.containsKey(letters[selectIndex]))
choose = selectIndex;
setDialogTextVisiable(VISIBLE);
}
}
break;
case MotionEvent.ACTION_MOVE:
if (oldChoose != selectIndex) {
if (selectIndex >= 0 && selectIndex < letters.length) {
if (alphaIndexer.containsKey(letters[selectIndex]))
choose = selectIndex;
setDialogTextVisiable(VISIBLE);
}
}
break;
case MotionEvent.ACTION_UP:
setDialogTextVisiable(INVISIBLE);
break;
default:
break;
}
return super.onTouchEvent(event);
}
private void setDialogTextVisiable(final int visiable) {
if (mHandler != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (mDialogText != null) {
mDialogText.setVisibility(visiable);
}
}
});
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int height = getHeight();
int width = getWidth();
int sigleHeight = height / letters.length; // 单个字母占的高度
for (int i = 0; i < letters.length; i++) {
paint.setColor(Color.parseColor("#b68036")); // 正常字母颜色
paint.setTextSize(getResources().getDimension(R.dimen.textSize_s5));
paint.setAntiAlias(true);
if (i == choose) {
paint.setColor(Color.parseColor("#FF0000")); // 滑动时按下字母颜色
paint.setFakeBoldText(true);
}
if (alphaIndexer == null) {
return;
}
if (!alphaIndexer.containsKey(letters[i])) {
paint.setColor(Color.parseColor("#bbbbbb")); // 没有对应联系人的首字母灰显的颜色
paint.setFakeBoldText(true);
}
// 绘画的位置
float xPos = width / 2 - paint.measureText(letters[i]) / 2;
float yPos = sigleHeight * i + sigleHeight;
canvas.drawText(letters[i], xPos, yPos, paint);
paint.reset();
}
}
}
然后就看导入操作的布局文件把
importing_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="@drawable/shape_rect_dialog"
android:layout_width="200dp"
android:layout_height="133.33dp">
<TextView
android:id="@+id/tv_person"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_centerHorizontal="true"
android:textSize="@dimen/textSize_s2"
android:textColor="@color/b3"
android:layout_centerVertical="true"/>
<com.example.contactdemo.CustomProgressBar
android:id="@+id/progress"
android:layout_width="180dip"
android:layout_height="10dip"
android:layout_below="@id/tv_person"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="@drawable/pro_line"/>
<ImageView
android:id="@+id/import_succ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/check_blue"
android:visibility="invisible"
android:layout_centerInParent="true"/>
<TextView
android:id="@+id/tv_succ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/import_succ"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="导入成功!"
android:textSize="@dimen/textSize_s2"
android:visibility="invisible"
android:textColor="@color/b3"/>
</RelativeLayout>
package com.example.contactdemo;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
public class ImportingDialog extends Dialog implements ReadDataListener {
private static final String LOG_TAG = ImportingDialog.class.getSimpleName();
private static final String TAG = "ImportingDialog";
private TextView tv_person, tv_succ;
private ImageView image_succ;
private int mPercent = 0;
CustomProgressBar mCustomProgressBar = null;
public ImportingDialog(Context c) {
super(c, R.style.dialog);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.importing_layout);
tv_person = (TextView) findViewById(R.id.tv_person);
mCustomProgressBar = (CustomProgressBar) findViewById(R.id.progress);
tv_succ = (TextView) findViewById(R.id.tv_succ);
image_succ = (ImageView) findViewById(R.id.import_succ);
mCustomProgressBar.setProgress(0);
}
public void notifyByteProgress(int totalByte, int readByte) {
Log.d(TAG, "notifyByteProgress totalByte=" + totalByte + " , readByte="
+ readByte);
final int percent = (int) ((double) readByte / totalByte * 100);
if (percent == mPercent) {
return;
}
tv_person.setText(readByte + "/" + totalByte);
mCustomProgressBar.setProgress(percent);
}
public void onComplete() {
tv_person.setVisibility(View.GONE);
mCustomProgressBar.setVisibility(View.GONE);
tv_succ.setVisibility(View.VISIBLE);
image_succ.setVisibility(View.VISIBLE);
}
}
ReadDataListener
package com.example.contactdemo;
/**
* @author chao
*
*/
public interface ReadDataListener {
/**
* this method can't execute pass-time operation.
*
* @param totalByte
* @param readByte
*/
public void notifyByteProgress(int totalByte, int readByte);
public void onComplete();
}
CustomProgressBar
package com.example.contactdemo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
public class CustomProgressBar extends View {
int width;
int height;
Bitmap sourBg;
Bitmap barBg;
boolean isInit = false;
int currProgress = 0;
Handler closeViewHandler = new Handler() {
public void handleMessage(Message msg) {
if (CustomProgressBar.this.currProgress == 100) {
CustomProgressBar.this.setVisibility(View.GONE);
CustomProgressBar.this.currProgress = 0;
}
super.handleMessage(msg);
}
};
/**
* 构造方法
*
* @param ctx
*/
public CustomProgressBar(Context ctx) {
super(ctx);
}
public CustomProgressBar(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
this.width = getWidth();
this.height = getHeight();
this.sourBg = BitmapFactory.decodeResource(getResources(),
R.drawable.pro_state);
this.sourBg = conBitmapSize(this.sourBg, this.width, this.height);
this.isInit = true;
if (this.currProgress > 0) {
setProgress(this.currProgress);
}
super.onSizeChanged(w, h, oldw, oldh);
}
/**
* @param bitmap
* 进度的背景图片
* @param width
* 控件宽
* @param height
* 控件高
* @return
*/
private Bitmap conBitmapSize(Bitmap bitmap, int width, int height) {
Matrix matrix = new Matrix();
matrix.setScale(1.0F * width / bitmap.getWidth(), 1.0F * height
/ bitmap.getHeight());
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, false);
return bitmap;
}
protected void onDraw(Canvas canvas) {
if ((this.barBg != null) && (this.isInit)) {
canvas.drawBitmap(this.barBg, 0.0F, 0.0F, null);
}
super.onDraw(canvas);
}
/**
* (1)0 -------- VISIBLE 可见
* (1)4 -------- INVISIBLE 不可见但是占用布局空间
* (1)8 -------- GONE 不可见也不占用布局空间
*/
public void setProgress(int progress) {
try {
this.currProgress = progress;
if (!this.isInit) {
setVisibility(View.VISIBLE);
return;
}
int vis = getVisibility();
if (vis == 8) {
setVisibility(View.VISIBLE);
}
int ferWidth = (int) Math.ceil(progress / 100.0F * this.width);
if (ferWidth == 0) {
ferWidth = 10;
}
if (this.sourBg != null) {
this.barBg = cutBitmap(this.sourBg, ferWidth, this.height);
this.barBg = toRoundCorner(this.barBg,
dip2px(getContext(), 4.33f));// 4.33f表示进度条的圆角大小
invalidate();
} else {
setVisibility(View.GONE);
}
if (progress >= 100)
this.closeViewHandler.sendMessageDelayed(
this.closeViewHandler.obtainMessage(1000), 0L);
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
int color = 0xff424242;
Paint paint = new Paint();
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
RectF rectF = new RectF(rect);
float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
private Bitmap cutBitmap(Bitmap bitmap, int width, int height) {
Bitmap cutBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
return cutBitmap;
}
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
package com.example.contactdemo;
import java.util.ArrayList;
/**
* Created by Administrator on 2016/4/13.
*/
public class ContactMember {
private String contactName;
private ArrayList<String> contactPhones;
private long contactId;
private String sortKey;//用于排序
private boolean isCheck;
public ContactMember(){
}
public ContactMember(String contactName,long contactId,String sortKey,ArrayList<String> contactPhones){
this.contactName=contactName;
this.contactId=contactId;
this.sortKey=sortKey;
this.contactPhones=contactPhones;
}
public long getContactId() {
return contactId;
}
public String getContactName() {
return contactName;
}
public String getSortKey() {
return sortKey;
}
public void setContactId(long contactId) {
this.contactId = contactId;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public void setSortKey(String sortKey) {
this.sortKey = sortKey;
}
public ArrayList<String> getContactPhones() {
return contactPhones;
}
public void setContactPhones(ArrayList<String> contactPhones) {
this.contactPhones = contactPhones;
}
public boolean isCheck() {
return isCheck;
}
public void setIsCheck(boolean isCheck) {
this.isCheck = isCheck;
}
}
DataBaseHelper
package com.example.contactdemo;
import java.util.ArrayList;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper {
/**
* 数据库名字
*/
private static final String DATABASE_NAME = "geek.db";
/**
* 学生信息表名
*/
public static final String TABLE_NAME_CONTACT = "contact";
private static int version = 1;
// 构造器
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, version);
}
// 带版本更新的构造器
public DataBaseHelper(Context context, int version) {
super(context, DATABASE_NAME, null, version);
DataBaseHelper.version = version;
}
@Override
public void onCreate(SQLiteDatabase db) {
createTables(db);
}
void createTables(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME_CONTACT + " ("
+ BaseColum.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ BaseColum.NAME + " TEXT, "
+ BaseColum.PHONE+ " TEXT, "
+ BaseColum.CONTACT_ID + " LONG" + ")";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/**
* 学生信息表字段名
*
*/
static class BaseColum {
public static final String ID = "id";
public static final String CONTACT_ID = "contactId";
public static final String NAME = "name";
public static final String PHONE = "phone";
}
}
package com.example.contactdemo;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class VChatSipInfoStorage {
private DataBaseHelper mDataBaseHelper;
private SQLiteDatabase mSQLitedb;
private static VChatSipInfoStorage mInstance;
private long insert;
public static VChatSipInfoStorage getInstance() {
if (null == mInstance) {
synchronized (VChatSipInfoStorage.class) {
if (null == mInstance) {
mInstance = new VChatSipInfoStorage();
}
}
}
return mInstance;
}
private VChatSipInfoStorage() {
super();
if (mSQLitedb == null) {
openDataBase(MyApplication.getInstance());
}
}
private void openDataBase(Context context) {
if (mDataBaseHelper == null) {
mDataBaseHelper = new DataBaseHelper(context);
}
if (mSQLitedb == null) {
mSQLitedb = mDataBaseHelper.getWritableDatabase();
}
}
/**
* 插入数据 插入所有列
*
* public static final String ID = "id";
public static final String CONTACT_ID = "contactId";
public static final String NAME = "name";
public static final String PHONE = "phone";
*/
public void insertStuAllColumn(ContactMember member) {
// 准备数据
ArrayList<String> contactPhones = member.getContactPhones();
if (contactPhones!=null && contactPhones.size()>0) {
for (int i = 0; i < contactPhones.size(); i++) {
Log.i("VChatSipInfoStorage", "VChatSipInfoStorage insert");
ContentValues values = new ContentValues();
values.put("name", member.getContactName());
values.put("phone", contactPhones.get(i));
values.put("contactId", member.getContactId());
insert = mSQLitedb.insert(DataBaseHelper.TABLE_NAME_CONTACT, null, values);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.i("VChatSipInfoStorage", "insert:"+insert);
}
}
}
MyApplication
package com.example.contactdemo;
import android.app.Application;
public class MyApplication extends Application{
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
this.instance = this;
}
public static MyApplication getInstance(){
return instance;
}
}
package com.example.contactdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Pattern;
/**
* simple tools to handle text for apps.
*
*/
public class TextUtil {
/**
* 判断字符串是否为空
*
* @param str
* @return
*/
public static boolean isEmpty(CharSequence str) {
if (str == null || str.length() == 0) {
return true;
}
return false;
}
/**
* 判断字符串是否全为数字
*
* @param str
* @return
*/
public static boolean isNumberic(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
}
rounded_search_text.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#FFFFFF" />
<corners
android:bottomLeftRadius="4dp"
android:bottomRightRadius="4dp"
android:topLeftRadius="4dp"
android:topRightRadius="4dp" />
</shape><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:drawable="@drawable/check_blue" /><!--选中时效果-->
<item android:state_checked="false"
android:drawable="@drawable/unchecked" /><!--未选中时效果-->
</selector> <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/top_return_p" android:state_pressed="true"/>
<!-- pressed -->
<item android:drawable="@drawable/top_return_p" android:state_selected="true"/>
<!-- focused -->
<item android:drawable="@drawable/top_return_n"/>
<!-- default -->
</selector><?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<corners android:radius="5dp"/>
<solid android:color="@color/bg3"/>
</shape>原文:http://blog.csdn.net/u013210620/article/details/51250542