完整项目介绍看这里:安卓项目SimpleQQ概述,可下载源码。
单个联系人布局文件:person_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_word"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#edecec"
android:textColor="#b6b4b4"
android:gravity="center_vertical"
android:paddingLeft="?android:attr/listPreferredItemPaddingLeft" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp" >
<ImageView
android:id="@+id/tv_headImg"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:focusable="false"
android:background="@drawable/head_2"
android:layout_width="50dp"
android:layout_height="match_parent"/>
<TextView
android:id="@+id/tv_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
android:paddingRight="?android:attr/listPreferredItemPaddingRight"
android:textAppearance="?android:attr/textAppearanceListItemSmall" />
LinearLayout>
LinearLayout>
联系人列表ListView:person_list.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#fff"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" />
<com.example.yangenneng0.myapplication.utils.WordsNavigation
android:id="@+id/words"
android:layout_width="30dp"
android:layout_marginRight="0dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true" />
<TextView
android:id="@+id/tv"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="@color/colorPrimary"
android:gravity="center"
android:textColor="#ffffff"
android:textSize="40sp"
android:visibility="gone" />
RelativeLayout>
联系人实体类:Person
package com.example.yangenneng0.myapplication.model;
import com.example.yangenneng0.myapplication.utils.PinYinUtils;
/**
* User: yangenneng
* DateTime: 2016/12/13 10:43
* Description:好友实体类
*/
public class Person {
private String name; //姓名
private String pinyin;//拼音
private String headerWord; //拼音首字母
private String username;//用户名
private String password;//密码
public Person(){}
public Person(String name){
this.name=name;
this.password="";
this.username="";
this.pinyin = PinYinUtils.getPinyin(name);
headerWord = pinyin.substring(0, 1);
}
public Person(String name,String username,String password) {
this.username=username;
this.password=password;
this.name = name;
this.pinyin = PinYinUtils.getPinyin(name);
headerWord = pinyin.substring(0, 1);
}
public String getPinyin() {
return pinyin;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeaderWord() {
return headerWord;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
联系人数据访问对象:PersonDAO
package com.example.yangenneng0.myapplication.dao;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.yangenneng0.myapplication.db.DbConnection;
import com.example.yangenneng0.myapplication.model.Person;
import java.util.ArrayList;
/**
* User: yangenneng
* DateTime: 2016/12/17 15:25
* Description:联系人数据访问对象
*/
public class PersonDAO {
private static ArrayList personList=null;//保存联系人数据
//获取所有联系人
public static ArrayList getPersonList(){
if(null==personList){
synchronized ( PersonDAO.class ){
if(null==personList){
personList=new ArrayList();
}
}
//把数据库中已有的数据拿出来
DbConnection connection=new DbConnection();
SQLiteDatabase db=connection.getConnection();
Cursor cursor=db.query("tb_person",null,null,null,null,null,null);
while ( cursor.moveToNext() ){
int namenum=cursor.getColumnIndex("name");
int usernamenum=cursor.getColumnIndex("username");
int passwordnum=cursor.getColumnIndex("password");
String name=cursor.getString(namenum);
String username=cursor.getString(usernamenum);
String password=cursor.getString(passwordnum);
Person person=new Person(name,username,password);
personList.add(person);
cursor.moveToNext();
}
}
return personList;
}
/**
* 根据用户名查找用户真实姓名
* @param username
* @return
*/
public static String findNameByUsername(String username){
if(null==personList){
getPersonList();
}
for ( int i = 0; i < personList.size(); i++ ) {
Person person=personList.get(i);
if(username.equals(person.getUsername())){
return person.getName();
}
}
return "";
}
/**
* 查找用户名是否存在
* @param username
* @return
*/
public boolean checkUsername(String username){
if(null==personList){
getPersonList();
}
for ( int i = 0; i < personList.size(); i++ ) {
Person book=personList.get(i);
if(username.equals(book.getUsername())){
return true;
}
}
return false;
}
/**
* 插入联系人
* @param person
* @return
*/
public boolean insert(Person person){
if(checkUsername(person.getUsername())){ //如果用户名存在则直接返回失败
return false;
}
try {
personList.add(person);
DbConnection conn=new DbConnection();
SQLiteDatabase db=conn.getConnection();
String sql="insert into tb_person(name,username,password) values('"
+person.getName()+"','"+person.getUsername()+"','"+person.getPassword()+"')";
db.execSQL(sql);
db.close();
return true;
}catch ( Exception e ){
return false;
}
}
public boolean chechLogin(String username,String password){
if(null==personList){
getPersonList();
}
for ( int i = 0; i < personList.size(); i++ ) {
Person book=personList.get(i);
if(username.equals(book.getUsername()) && password.equals(book.getPassword())){
return true;
}
}
return false;
}
}
联系人列表适配器:PersonAdapter
package com.example.yangenneng0.myapplication.adapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.yangenneng0.myapplication.R;
import com.example.yangenneng0.myapplication.model.Person;
import com.example.yangenneng0.myapplication.viewUI.ChatMainActivity;
import java.util.List;
/**
* User: yangenneng
* DateTime: 2016/12/13 10:41
* Description:联系人ListView列表适配器
*/
public class PersonAdapter extends BaseAdapter {
private Context context;//为了实现跳转而写的
private List list;//联系人列表
private LayoutInflater inflater;
public PersonAdapter(Context context, List list) {
inflater = LayoutInflater.from(context);
this.context=context;//为了实现跳转而写的
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder; //ViewHolder是自定义内部内类
if(null==convertView){
holder= new ViewHolder();
convertView=inflater.inflate(R.layout.person_list_item,null); //单个联系人
holder.tv_name= (TextView) convertView.findViewById(R.id.tv_name); //姓名
holder.tv_word= (TextView) convertView.findViewById(R.id.tv_word); //名字字母
convertView.setTag(holder);
}else {
holder= (ViewHolder) convertView.getTag();
}
String word=list.get(position).getHeaderWord();//第一个字母
holder.tv_word.setText(word);
holder.tv_name.setText(list.get(position).getName());
//跳转到聊天页面
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(context,ChatMainActivity.class);
Bundle bundle = new Bundle();//传递过去的用户参数
bundle.putString("name", (list.get(position).getName()));
intent.putExtras(bundle);
context.startActivity(intent);
//
//Intent intent=new Intent();
//intent.setClass(context,ChatMainActivity.class);
//context.startActivity(intent);
提示当前点击的是哪个类
//Snackbar.make(v, "position:"+position, Snackbar.LENGTH_LONG) .setAction("Action", null).show();
}
});
//将相同字母开头的合并在一起
if(position==0){
//第一个是一定显示的
holder.tv_word.setVisibility(View.VISIBLE);
}else {
//后一个与前一个对比,判断首字母是否相同,相同则隐藏
String headword=list.get(position-1).getHeaderWord();
if(word.equals(headword)){
holder.tv_word.setVisibility(View.GONE);
}else {
holder.tv_word.setVisibility(View.VISIBLE);
}
}
return convertView;
}
private class ViewHolder {
private TextView tv_word;
private TextView tv_name;
}
}
联系人主页:MainActivity
package com.example.yangenneng0.myapplication;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.yangenneng0.myapplication.adapter.PersonAdapter;
import com.example.yangenneng0.myapplication.dao.PersonDAO;
import com.example.yangenneng0.myapplication.model.Person;
import com.example.yangenneng0.myapplication.utils.*;
import com.example.yangenneng0.myapplication.viewUI.QQmoodActivity;
import com.example.yangenneng0.myapplication.viewUI.QzoneActivity;
import com.example.yangenneng0.myapplication.viewUI.RegistActivity;
import com.example.yangenneng0.myapplication.viewUI.SettingsActivity;
import com.getbase.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* 功能:软件主界面类
*/
public class MainActivity extends AppCompatActivity
implements WordsNavigation.onWordsChangeListener,
NavigationView.OnNavigationItemSelectedListener , AbsListView.OnScrollListener{
//侧拉菜单滑出来的那一部分属于NavigationView
private static boolean isExit=false;//判断是否直接退出程序
//---联系人列表属性
private Handler handler; //
private List list; //联系人列表基本信息
private TextView tv; //绘制的字母
private ListView listView; //使用适配器的联系人列表
private WordsNavigation word; //右侧字母导航
//---联系人列表属性
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*--------------联系人 begin--------------*/
tv = (TextView) findViewById(R.id.tv);
word = (WordsNavigation) findViewById(R.id.words);
listView = (ListView) findViewById(R.id.list);
initData();//初始化联系人数据
initListView();//初始化联系人列表
handler = new Handler();//设置列表点击滑动监听
word.setOnWordsChangeListener(this);
/*--------------联系人 end--------------*/
//顶部工具栏
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Android侧滑菜单DrawerLayout
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//ActionBarDrawerToggle监听Drawer拉出、隐藏
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
//设置左侧菜单
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//发表说说
FloatingActionButton button= (FloatingActionButton) findViewById(R.id.button_mood);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, QQmoodActivity.class);
MainActivity.this.startActivity(intent);
}
});
//浏览空间
FloatingActionButton button2= (FloatingActionButton) findViewById(R.id.button_qzone);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, QzoneActivity.class);
MainActivity.this.startActivity(intent);
}
});
//给左侧导航赋值当前登录用户名
//TextView loginName= (TextView) findViewById(R.id.loginname);
//loginName.setText(APPglobal.USERNAME);
}
/**
* 取Back键的按下事件
*/
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if ( drawer.isDrawerOpen(GravityCompat.START) ) {
drawer.closeDrawer(GravityCompat.START); //如果左侧导航打开,单机Back键时关闭左侧导航
} else {
super.onBackPressed();//如果左侧导航关闭,,单机Back键时退出程序
}
}
/**
* 用于初始化菜单 (只会在第一次初始化菜单时调用)
* @param menu 即将要显示的Menu实例
* @return 返回true则显示该menu, false 则不显示
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* 菜单项被点击时调用,也就是菜单项的监听方法。
* @param item 菜单项点击的子菜单
* @return
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if ( id == R.id.action_settings ) { //安全退出
Intent intent = new Intent();
intent.setClass(MainActivity.this, LoginActivity.class);
MainActivity.this.startActivity(intent);
return true;
}
if ( id == R.id.action_regist ) { //立即注册
Intent intent = new Intent();
intent.setClass(MainActivity.this, RegistActivity.class);
MainActivity.this.startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 左侧导航被选择时触发的事件
* @param item 左侧选中的菜单
* @return
*/
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if ( id == R.id.nav_camera ) {//拍照
// Handle the camera action
Intent intent=new Intent();
intent.setClass(MainActivity.this,CameraActivity.class);
MainActivity.this.startActivity(intent);
} else if ( id == R.id.nav_gallery ) { //相册 获取指定目录下的所有照片
Intent intent = new Intent(Intent.ACTION_VIEW);
String type = "image/*";
Uri uri = Uri.parse("file:///sdcard/QQ_Test/");
intent.setDataAndType(uri, type);
startActivity(intent);
} else if ( id == R.id.nav_slideshow ) { //视频 调用视频播放器播放指定的视频
Intent intent = new Intent(Intent.ACTION_VIEW);
String type = "video/mp4";
Uri uri = Uri.parse("file:///sdcard/QQ_TEST_Video/03简单句的补充.mp4");
intent.setDataAndType(uri, type);
startActivity(intent);
} else if ( id == R.id.nav_manage ) { //系统设置
Intent intent = new Intent();
intent.setClass(MainActivity.this, SettingsActivity.class);
MainActivity.this.startActivity(intent);
} else if ( id == R.id.nav_share ) { //分享软件
Intent intent = new Intent();
intent.setClass(MainActivity.this, MessageActivity.class);
MainActivity.this.startActivity(intent);
} else if ( id == R.id.nav_send ) { //地理位置
Intent intent = new Intent();
intent.setClass(MainActivity.this, MapActivity.class);
MainActivity.this.startActivity(intent);
}
//选择之后关闭左侧导航
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* 继承 WordsNavigation.onWordsChangeListener 手指按下字母改变监听回调
* @param words 按下的字母
*/
@Override
public void wordsChange(String words) {
updateWord(words); //更新字母
updateListView(words); //更新列表
}
/**
* 初始化好友列表
*/
private void initListView() {
PersonAdapter adapter = new PersonAdapter(this, list);
listView.setAdapter(adapter);
listView.setOnScrollListener(this);
}
/**
* 初始化联系人列表信息
*/
private void initData() {
list = new ArrayList<>();
//list.add(new Person("Dave"));
//list.add(new Person("张晓飞"));
//list.add(new Person("杨光福"));
//list.add(new Person("阿钟"));
//list.add(new Person("胡继群"));
//list.add(new Person("徐歌阳"));
//list.add(new Person("钟泽兴"));
//list.add(new Person("宋浮点"));
//list.add(new Person("刘俄式"));
//list.add(new Person("Tony"));
//list.add(new Person("老刘"));
//list.add(new Person("葛优"));
//list.add(new Person("安传鑫"));
//list.add(new Person("温松"));
//list.add(new Person("成龙"));
//list.add(new Person("那英"));
//list.add(new Person("刘甫"));
//list.add(new Person("沙宝亮"));
//list.add(new Person("张梁"));
//list.add(new Person("张大爷"));
//list.add(new Person("张哥"));
//list.add(new Person("张娃"));
//list.add(new Person("张丽"));
//list.add(new Person("吴亮"));
//list.add(new Person("Tom"));
//list.add(new Person("安在"));
//list.add(new Person("小李"));
//list.add(new Person("贝阿朵"));
//list.add(new Person("赵二喜"));
//list.add(new Person("阿道夫"));
//list.add(new Person("姜宇航"));
list= PersonDAO.getPersonList();
//对集合排序:按字母顺序排序
Collections.sort(list, new Comparator() {
@Override
public int compare(Person lhs, Person rhs) {
//根据拼音进行排序
return lhs.getPinyin().compareTo(rhs.getPinyin());
}
});
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
/**
*
* @param view
* @param firstVisibleItem
* @param visibleItemCount
* @param totalItemCount
*/
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//当滑动列表的时候,更新右侧字母列表的选中状态
word.setTouchIndex(list.get(firstVisibleItem).getHeaderWord());
}
/**
* 根据右侧的选中字母重新排序中间联系人的选中
* 把那个字母的联系人的第一个找到就可以了 设置那个时候的选中状态为那个位置
* @param words 首字母
*/
private void updateListView(String words) {
for (int i = 0; i < list.size(); i++) {
String headerWord = list.get(i).getHeaderWord();
//将手指按下的字母与列表中相同字母开头的项找出来
if (words.equals(headerWord)) {
//将列表选中哪一个
listView.setSelection(i);
//找到开头的一个即可
return;
}
}
}
/**
* 更新中央的字母提示
* @param words 首字母
*/
private void updateWord(String words) {
tv.setText(words);
tv.setVisibility(View.VISIBLE);
//清空之前的所有消息
handler.removeCallbacksAndMessages(null);
//1s后让tv隐藏
handler.postDelayed(new Runnable() {
@Override
public void run() {
tv.setVisibility(View.GONE);
}
}, 500);//绘制的画面停留0.5s
}
Handler myhandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
isExit=false;
}
};
//退出确认
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK){
if(!isExit){
isExit=true;
Toast.makeText(getApplicationContext(),"再按一次退出程序",Toast.LENGTH_SHORT).show();
myhandler.sendEmptyMessageDelayed(0,2000);
}
}else {
finish();
System.exit(0);
}
return super.onKeyDown(keyCode, event);
}
}
获取汉字的拼音:PinYinUtils
package com.example.yangenneng0.myapplication.utils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
/**
* User: yangenneng
* DateTime: 2016/12/13 10:44
* Description:得到指定汉字的拼音
*/
public class PinYinUtils {
public static String getPinyin(String hanzi){
StringBuffer sb=new StringBuffer();
HanyuPinyinOutputFormat format=new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
//由于不能直接对多个汉子转换,只能对单个汉子转换
char[] arr=hanzi.toCharArray();
for ( int i = 0; i < arr.length; i++ ) {
if(Character.isWhitespace(arr[i])){//如果是空格
continue;
}
try {
String[] pinyinArr= PinyinHelper.toHanyuPinyinStringArray(arr[i],format);
if(pinyinArr!=null)sb.append(pinyinArr[0]);
else sb.append(arr[i]);
} catch ( BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination ) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
//不是正确的汉字
sb.append(arr[i]);
}
}
return sb.toString();
}
}
联系人右侧字母导航:WordsNavigation
package com.example.yangenneng0.myapplication.utils;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* User: yangenneng
* DateTime: 2016/12/13 11:14
* Description:实现手机联系人列表导航
*/
public class WordsNavigation extends View {
/*绘制的列表导航字母*/
private String words[] = {"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 Paint wordsPaint; //字母画笔
private Paint bgPaint; //字母背景画笔
private int itemWidth; //每一个字母的宽度
private int itemHeight; //每一个字母的高度
private int touchIndex = 0; //手指按下的字母索引
private onWordsChangeListener listener;//自定义类 手指按下的字母改变接口
/**
* 初始化画笔
*/
private void init(){
//字母画笔
wordsPaint=new Paint();
wordsPaint.setColor(Color.parseColor("#F7F7F7"));
wordsPaint.setAntiAlias(true);
wordsPaint.setTextSize(40);
wordsPaint.setTypeface(Typeface.DEFAULT_BOLD);
//字母背景画笔
bgPaint = new Paint();
bgPaint.setAntiAlias(true);
bgPaint.setColor(Color.parseColor("#1dcdef"));
}
/*---------------继承View类自动生成的类 begin------------------*/
public WordsNavigation(Context context) {
super(context);
init();
}
public WordsNavigation(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public WordsNavigation(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
/*-----------------继承View类自动生成 end----------------*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
itemWidth=getMeasuredWidth();
int height = getMeasuredHeight() - 10; //使得边距好看一些
itemHeight = height / 27;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < words.length; i++) {
if (touchIndex == i) {//判断是不是我们按下的当前字母
//绘制文字圆形背景
canvas.drawCircle(itemWidth / 2, itemHeight / 2 + i * itemHeight, 23, bgPaint);
wordsPaint.setColor(Color.WHITE);//当前按下的是白色字体
} else {
wordsPaint.setColor(Color.GRAY); //否则为黑色字体
}
//获取文字的宽高
Rect rect = new Rect();
wordsPaint.getTextBounds(words[i], 0, 1, rect);
int wordWidth = rect.width();
//绘制字母
float wordX = itemWidth / 2 - wordWidth / 2;
float wordY = itemWidth / 2 + i * itemHeight;
canvas.drawText(words[i], wordX, wordY, wordsPaint);
}
}
/**
* 当手指触摸按下的时候改变字母背景颜色
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
float y = event.getY();
//获得我们按下的是那个索引(字母)
int index = (int) (y / itemHeight);
if (index != touchIndex)
touchIndex = index;
//防止数组越界
if (listener != null && 0 <= touchIndex && touchIndex <= words.length - 1) {
//回调按下的字母
listener.wordsChange(words[touchIndex]);
}
invalidate();
break;
case MotionEvent.ACTION_UP:
//手指抬起,不做任何操作
break;
}
return true;
}
/**
* 设置当前按下的是那个字母
* @param word
*/
public void setTouchIndex(String word) {
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word)) {
touchIndex = i;
invalidate();
return;
}
}
}
/**
* 手指按下了哪个字母的回调接口
*/
public interface onWordsChangeListener {
void wordsChange(String words);
}
/*设置手指按下字母改变监听*/
public void setOnWordsChangeListener(onWordsChangeListener listener) {
this.listener = listener;
}
}