出处是:
https://github.com/luckyandyzhang/MentionEditText
我在这个大神的基础上修改的
复制以下代码,然后找个拼音jar包,就能出来效果了
注:有个问题我解决不了,当光标在文字中间的时候,@一个人,回来,光标就到了文本的最后了。我试过,改不了。如果有哪个大神知道怎么解决,请告我一下,谢谢了。
排序需要的jar包(pinyin4j-2.5.0.jar),我上传失败了。如果有需要,网上找个,或者加我qq:2904530975,我发
效果图(不会搞动态的,就用静态的了):
———————–图片分割线—————————————
代码:
Edittext中输入@符号关联联系人
1、MentionEditText
package com.chen.demo;
import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MentionEditText extends EditText {
private Pattern mPattern;
private Runnable mAction;
private int mMentionTextColor;
private boolean mIsSelected;
private Range mLastSelectedRange;
private List<Range> mRangeArrayList;
/**
* 输入@符号的监听器
*/
private OnMentionInputListener mOnMentionInputListener;
/**
* 文字内容长度的监听器
*/
private TextLengthlistener textLengthlistener;
/**
* 输入了多少个@的监听器
*/
private AttentionPersonNumListener attentionPersonNumListener;
public MentionEditText(Context context) {
super(context);
init();
}
public MentionEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MentionEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
//这里不知道什么意思,不太懂
mRangeArrayList = new ArrayList<>(5);
mPattern = Pattern.compile(Chen.regex);
mMentionTextColor = Color.parseColor(Chen.nameColor);
//disable suggestion
// setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
addTextChangedListener(new MentionTextWatcher());
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return new HackInputConnection(super.onCreateInputConnection(outAttrs), true, this);
}
@Override
public void setText(final CharSequence text, BufferType type) {
super.setText(text, type);
//hack, put the cursor at the end of text after calling setText() method
if (mAction == null) {
mAction = new Runnable() {
@Override
public void run() {
setSelection(getText().length());
}
};
}
post(mAction);
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
colorMentionString();
}
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
super.onSelectionChanged(selStart, selEnd);
//avoid infinite recursion after calling setSelection()
if (mLastSelectedRange != null && mLastSelectedRange.isEqual(selStart, selEnd)) {
return;
}
//if user cancel a selection of mention string, reset the state of 'mIsSelected'
Range closestRange = getRangeOfClosestMentionString(selStart, selEnd);
if (closestRange != null && closestRange.to == selEnd) {
mIsSelected = false;
}
Range nearbyRange = getRangeOfNearbyMentionString(selStart, selEnd);
//if there is no mention string nearby the cursor, just skip
if (nearbyRange == null) {
return;
}
//forbid cursor located in the mention string.
if (selStart == selEnd) {
setSelection(nearbyRange.getAnchorPosition(selStart));
} else {
if (selEnd < nearbyRange.to) {
setSelection(selStart, nearbyRange.to);
}
if (selStart > nearbyRange.from) {
setSelection(nearbyRange.from, selEnd);
}
}
}
/**
* 设置正则匹配的规则
*
* @param pattern 正则匹配的规则
*/
public void setPattern(String pattern) {
mPattern = Pattern.compile(pattern);
}
/**
* 设置@的人名的颜色
*
* @param color
*/
public void setMentionTextColor(int color) {
mMentionTextColor = color;
}
/**
* 输入@的监听器
*
* @param onMentionInputListener
*/
public void setOnMentionInputListener(OnMentionInputListener onMentionInputListener) {
mOnMentionInputListener = onMentionInputListener;
}
private void colorMentionString() {
//reset state
mIsSelected = false;
if (mRangeArrayList != null) {
mRangeArrayList.clear();
}
Editable spannableText = getText();
if (spannableText == null || TextUtils.isEmpty(spannableText.toString())) {
return;
}
//remove previous spans
ForegroundColorSpan[] oldSpans = spannableText.getSpans(0, spannableText.length(), ForegroundColorSpan.class);
for (ForegroundColorSpan oldSpan : oldSpans) {
spannableText.removeSpan(oldSpan);
}
//find mention string and color it
int lastMentionIndex = -1;
String text = spannableText.toString();
Matcher matcher = mPattern.matcher(text);
while (matcher.find()) {
String mentionText = matcher.group();
int start;
if (lastMentionIndex != -1) {
start = text.indexOf(mentionText, lastMentionIndex);
} else {
start = text.indexOf(mentionText);
}
int end = start + mentionText.length();
spannableText.setSpan(new ForegroundColorSpan(mMentionTextColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
lastMentionIndex = end;
//record all mention-string's position
mRangeArrayList.add(new Range(start, end));
}
}
private Range getRangeOfClosestMentionString(int selStart, int selEnd) {
if (mRangeArrayList == null) {
return null;
}
for (Range range : mRangeArrayList) {
if (range.contains(selStart, selEnd)) {
return range;
}
}
return null;
}
private Range getRangeOfNearbyMentionString(int selStart, int selEnd) {
if (mRangeArrayList == null) {
return null;
}
for (Range range : mRangeArrayList) {
if (range.isWrappedBy(selStart, selEnd)) {
return range;
}
}
return null;
}
//text watcher for mention character('@')
private class MentionTextWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int index, int i1, int count) {
if (count == 1 && !TextUtils.isEmpty(charSequence)) {
char mentionChar = charSequence.toString().charAt(index);
if ('@' == mentionChar && mOnMentionInputListener != null) {
mOnMentionInputListener.onMentionCharacterInput();
}
}
if (textLengthlistener != null) {
textLengthlistener.onTextLength();
}
if (attentionPersonNumListener != null) {
attentionPersonNumListener.onPersonNum();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
}
//handle the deletion action for mention string, such as '@test'
private class HackInputConnection extends InputConnectionWrapper {
private EditText editText;
public HackInputConnection(InputConnection target, boolean mutable, MentionEditText editText) {
super(target, mutable);
this.editText = editText;
}
@Override
public boolean sendKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
int selectionStart = editText.getSelectionStart();
int selectionEnd = editText.getSelectionEnd();
Range closestRange = getRangeOfClosestMentionString(selectionStart, selectionEnd);
if (closestRange == null) {
mIsSelected = false;
return super.sendKeyEvent(event);
}
//if mention string has been selected or the cursor is at the beginning of mention string, just use default action(delete)
if (mIsSelected || selectionStart == closestRange.from) {
mIsSelected = false;
return super.sendKeyEvent(event);
} else {
//select the mention string
mIsSelected = true;
mLastSelectedRange = closestRange;
setSelection(closestRange.to, closestRange.from);
}
return true;
}
return super.sendKeyEvent(event);
}
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength) {
if (beforeLength == 1 && afterLength == 0) {
return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
&& sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
}
return super.deleteSurroundingText(beforeLength, afterLength);
}
}
//helper class to record the position of mention string in EditText
private class Range {
int from;
int to;
public Range(int from, int to) {
this.from = from;
this.to = to;
}
public boolean isWrappedBy(int start, int end) {
return (start > from && start < to) || (end > from && end < to);
}
public boolean contains(int start, int end) {
return from <= start && to >= end;
}
public boolean isEqual(int start, int end) {
return (from == start && to == end) || (from == end && to == start);
}
public int getAnchorPosition(int value) {
if ((value - from) - (to - value) >= 0) {
return to;
} else {
return from;
}
}
}
/**
* Listener for '@' character
*/
public interface OnMentionInputListener {
/**
* call when '@' character is inserted into EditText
*/
void onMentionCharacterInput();
}
public interface TextLengthlistener {
void onTextLength();
}
public void setTextLengthlistener(TextLengthlistener listener) {
textLengthlistener = listener;
}
public interface AttentionPersonNumListener {
void onPersonNum();
}
public void setAttentionPersonNumListener(AttentionPersonNumListener listener) {
attentionPersonNumListener = listener;
}
}
2、MainActivity
package com.chen.demo;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends Activity {
MentionEditText mention_et;
ImageView person_iv;
/**
* 点击@符号记录当前光标位置的变量
*/
int tempIndex = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mention_et = (MentionEditText) findViewById(R.id.mention_et);
person_iv = (ImageView) findViewById(R.id.person_iv);
//设置被@的人的名字展示的颜色
mention_et.setMentionTextColor(Color.parseColor(Chen.nameColor));
//设置匹配规则
mention_et.setPattern(Chen.regex);
//监听文本长度
mention_et.setTextLengthlistener(new MentionEditText.TextLengthlistener() {
@Override
public void onTextLength() {
}
});
//监听软键盘输入@符号
mention_et.setOnMentionInputListener(new MentionEditText.OnMentionInputListener() {
@Override
public void onMentionCharacterInput() {
tempIndex = mention_et.getSelectionStart();
Log.e("in_keyboard_tempIndex", tempIndex + "");
//startActivityForResult(Intent intent, int requestCode)
startActivityForResult(new Intent(MainActivity.this, AttentionPersonActivity.class), 111);
}
});
//监听@人的个数
mention_et.setAttentionPersonNumListener(new MentionEditText.AttentionPersonNumListener() {
@Override
public void onPersonNum() {
}
});
//点击软键盘外的@符号
person_iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tempIndex = mention_et.getSelectionStart();
Log.e("out_keyboard_tempIndex", tempIndex + "");
startActivityForResult(new Intent(MainActivity.this, AttentionPersonActivity.class), 222);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 111 && resultCode == 456456) {
//点击软键盘上的@符号回来的
String text = mention_et.getText().toString();
String name = data.getStringExtra("name");
if (tempIndex == 0) {
text = name + " " + text;
} else if (tempIndex == text.length()) {
text = text + name + " ";
} else {
String s1 = text.substring(0, tempIndex);
String s2 = text.substring(tempIndex, text.length());
text = s1 + name + " " + s2;
}
mention_et.setText(text);
}
if (requestCode == 222 && resultCode == 456456) {
//点击键盘外的@符号
String text = mention_et.getText().toString();
String name = data.getStringExtra("name");
if (tempIndex == 0) {
text = "@" + name + " " + text;
} else if (tempIndex == text.length()) {
text = text + "@" + name + " ";
} else {
String s1 = text.substring(0, tempIndex);
String s2 = text.substring(tempIndex, text.length());
text = s1 + "@" + name + " " + s2;
}
mention_et.setText(text);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
3、MainActivity的布局很简单:
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">
<com.chen.demo.MentionEditText
android:id="@+id/mention_et"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_margin="10dp"
android:gravity="top|left"
android:hint="说点什么吧"
android:textSize="20sp"/>
<ImageView
android:id="@+id/person_iv"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:background="@mipmap/link"/>
</LinearLayout>
4、第二个activity需要的东西准备
4.1
public class Chen {
//在Edittext中匹配人的名字。名字中允许出现 _ - 汉字 数字 英文 数字。且出现次数是在1-30之间。
public static String regex="@[_-\\u4E00-\\u9FA5\\w]{1,30}";
public static String nameColor="#3a76a6";
}
4.2、
public class Utils {
private static Toast toast;
public static void showSingleToast(Context context, String msg){
if(toast == null){
toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
}
toast.setText(msg);
toast.show();
}
/**
* 检查字符串是否是空
*
* @param str
* @return true:字符串为空
*/
public static boolean checkStringIsEmpty(String str) {
if (TextUtils.isEmpty(str) || "null".equals(str)) {
return true;
} else {
return false;
}
}
}
4.3、
/**
* chenjianqiang
* 选择关注人的回调接口
*/
public interface SelectAttentionPersonListener {
void personData(String name);
}
5、PersonBean,要注意它实现的接口和最后的排序
package com.chen.demo;
public class Person implements Comparable<Person>{
private String name;
private String pinyin;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPinyin() {
return pinyin;
}
public void setPinyin(String pinyin) {
this.pinyin = pinyin;
}
@Override
public int compareTo(Person another) {
return pinyin.compareTo(another.pinyin);
}
}
6、PinYinUtil
package com.chen.demo;
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;
public class PinYinUtil {
public static final String aa = "[0-9]";
public static String regex = "[-_a-z0-9`~!@#$%^&*()+=|{}':;',\\[\\].<>~!@#¥%……&*()——+|{}【】‘;:”“’。,、? ]";
/**
* 获取指定字符串的拼音
* @param strs
* @return
*/
public static String getPinyin(String strs) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
StringBuilder sb = new StringBuilder();
char[] charArray = strs.toCharArray();
for (int i = 0; i < charArray.length; i++) {
char c = charArray[i];
String s=c+"";
// 跳过空格和#
if(Character.isWhitespace(c)||s.matches(regex)){
continue;
}
// 直接添加特殊字符\字母\数字
if(c >= -128 && c < 127){
sb.append(c);
}else {
// 可能是汉字
try {
String str = PinyinHelper.toHanyuPinyinStringArray(c, format)[0];
sb.append(str);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
7、QuickIndexBar(快速索引自定义控件)
package com.chen.demo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* 快速索引
* chenjianqiang
*/
public class QuickIndexBar extends View {
public interface OnLetterUpdateListener {
void onLetterUpdate(String letter);
}
private OnLetterUpdateListener onLetterUpdateListener;
public OnLetterUpdateListener getOnLetterUpdateListener() {
return onLetterUpdateListener;
}
public void setOnLetterUpdateListener(
OnLetterUpdateListener onLetterUpdateListener) {
this.onLetterUpdateListener = onLetterUpdateListener;
}
private static final 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 Paint paint;
private int cellWidth;
private int mHeight;
private float cellHeight;
public QuickIndexBar(Context context) {
this(context, null);
}
public QuickIndexBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public QuickIndexBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// paint.setColor(Color.parseColor("#7e7e7e"));
paint.setColor(Color.parseColor("#7e7e7e"));
// 字体加粗
// paint.setTypeface(Typeface.DEFAULT_BOLD);
//单位是像素
paint.setTextSize(50);
}
@Override
protected void onDraw(Canvas canvas) {
// 将A-Z绘制到界面上
for (int i = 0; i < LETTERS.length; i++) {
String letter = LETTERS[i];
// 计算x , y坐标
float x = cellWidth / 2.0f - paint.measureText(letter) / 2.0f;
Rect bounds = new Rect();
paint.getTextBounds(letter, 0, letter.length(), bounds);
int textHeight = bounds.height();
float y = cellHeight * 0.5f + textHeight * 0.5f + i * cellHeight;
// paint.setColor(i == currentIndex ? Color.GRAY : Color.WHITE);
canvas.drawText(letter, x, y, paint);
}
}
private int currentIndex = -1;
@Override
public boolean onTouchEvent(MotionEvent event) {
int index = -1;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
index = (int) (event.getY() / cellHeight);
if (index >= 0 && index < LETTERS.length) {
if (currentIndex != index) {
String letter = LETTERS[index];
if (onLetterUpdateListener != null) {
onLetterUpdateListener.onLetterUpdate(letter);
}
currentIndex = index;
}
}
break;
case MotionEvent.ACTION_MOVE:
index = (int) (event.getY() / cellHeight);
if (index >= 0 && index < LETTERS.length) {
if (currentIndex != index) {
String letter = LETTERS[index];
if (onLetterUpdateListener != null) {
onLetterUpdateListener.onLetterUpdate(letter);
}
currentIndex = index;
}
}
break;
case MotionEvent.ACTION_UP:
currentIndex = -1;
break;
default:
break;
}
invalidate();
return true;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
cellWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
cellHeight = mHeight * 1.0f / LETTERS.length;
}
}
8、第二个activity的布局attention_person_activity
<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"
tools:context=".MainActivity">
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.chen.demo.QuickIndexBar
android:id="@+id/quick_index_bar"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_marginBottom="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
/>
</RelativeLayout>
9、展示人的Adapter引用的item布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_index"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f6f6f6"
android:gravity="center_vertical"
android:paddingBottom="5dp"
android:paddingLeft="15dp"
android:paddingTop="5dp"
android:text="Z"
android:textColor="#ff0000"
android:textSize="15sp"
/>
<TextView
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center_vertical"
android:paddingLeft="15dp"
android:text=""
android:textSize="20sp"/>
</LinearLayout>
10、NameAdapter(这里简单写了,没有加viewholder。实际是需要的)
package com.chen.demo;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class NameAdapter extends BaseAdapter {
private final ArrayList<Person> list;
private SelectAttentionPersonListener listener;
public NameAdapter(ArrayList<Person> list, SelectAttentionPersonListener listener) {
this.list = list;
this.listener = listener;
}
@Override
public int getCount() {
return list.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = View.inflate(parent.getContext(), R.layout.item_list_name, null);
} else {
view = convertView;
}
TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
TextView tv_index = (TextView) view.findViewById(R.id.tv_index);
Person person = list.get(position);
final String name = person.getName();
String currentIndexStr = person.getPinyin().charAt(0) + "";
String indexStr = null;
// 经过判断进行indexStr赋值
if (position == 0) {
// 1. 是首位
indexStr = currentIndexStr;
} else {
// 2. 当前首字母和上一个不一致
String lastBeanPinYin = list.get(position - 1).getPinyin();
String lastIndexStr = lastBeanPinYin.charAt(0) + "";
if (!TextUtils.equals(lastIndexStr, currentIndexStr)) {
// 不一致, 把当前字母赋给indexStr
indexStr = currentIndexStr;
}
}
tv_index.setVisibility(indexStr != null ? View.VISIBLE : View.GONE);
tv_index.setText(currentIndexStr);
tv_name.setText(name);
tv_name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.personData(name);
}
});
return view;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
11、AttentionPersonActivity
package com.chen.demo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Collections;
public class AttentionPersonActivity extends Activity implements SelectAttentionPersonListener {
ListView listview;
ArrayList<Person> list;
NameAdapter nameAdapter;
QuickIndexBar quick_index_bar;
ArrayList<String> nameList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.attention_person_activity);
listview = (ListView) findViewById(R.id.listview);
quick_index_bar = (QuickIndexBar) findViewById(R.id.quick_index_bar);
list = new ArrayList<>();
nameList = new ArrayList<>();
nameList.add("123456");
nameList.add("哈哈哈");
nameList.add("123哈哈");
nameList.add("哈哈456");
nameList.add("abcdef");
nameList.add("abc哈哈");
nameList.add("哈哈def");
nameList.add("ABC哈哈");
nameList.add("哈哈ABC");
nameList.add("得****得得");
nameList.add("_我们");
nameList.add("你们");
nameList.add("盖聂");
nameList.add("漩涡鸣人");
nameList.add("卡卡西");
nameList.add("鼬神");
nameList.add("佐助。");
nameList.add("雏.田");
nameList.add("=日=向=");
nameList.add("-斑");
nameList.add("三井寿");
nameList.add("小贤");
Person person;
String name;
for (int i = 0; i < nameList.size(); i++) {
person = new Person();
name = nameList.get(i);
person.setName(name);
//如果名字对应的拼音解析到了空值,就给个#号
if (!Utils.checkStringIsEmpty(PinYinUtil.getPinyin(name))) {
person.setPinyin(PinYinUtil.getPinyin(PinYinUtil.getPinyin(name)));
} else {
person.setPinyin("#");
}
list.add(person);
}
Collections.sort(list);
//第二个参数是回调接口
nameAdapter = new NameAdapter(list, this);
listview.setAdapter(nameAdapter);
quick_index_bar.setOnLetterUpdateListener(new QuickIndexBar.OnLetterUpdateListener() {
@Override
public void onLetterUpdate(String letter) {
Utils.showSingleToast(AttentionPersonActivity.this, letter);
for (int i = 0; i < list.size(); i++) {
String indexStr = list.get(i).getPinyin().charAt(0) + "";
if (TextUtils.equals(indexStr, letter)) {
// 匹配成功
//如果快速索引的最上面不是#,直接就是A开头,就不用+1了
listview.setSelection(i);
break;
}
}
}
});
}
@Override
public void personData(String name) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("name", name);
//setResult(int resultCode, Intent data)
setResult(456456, intent);
finish();
}
}
12、最后清单文件中(android:screenOrientation是禁止屏幕旋转的)
<activity
android:name=".AttentionPersonActivity"
android:screenOrientation="portrait"
/>