下面列出了怎么用android.widget.TextView.BufferType的API类实例代码及写法,或者点击链接到github查看源代码。
private void applySpacing() {
if (this != null && this.originalText != null) {
int i;
StringBuilder builder = new StringBuilder();
for (i = 0; i < this.originalText.length(); i++) {
builder.append(this.originalText.charAt(i));
if (i + 1 < this.originalText.length()) {
builder.append(" ");
}
}
SpannableString finalText = new SpannableString(builder.toString());
if (builder.toString().length() > 1) {
for (i = 1; i < builder.toString().length(); i += 2) {
finalText.setSpan(new ScaleXSpan((this.spacing + 1.0f) / 10.0f), i, i + 1, 33);
}
}
super.setText(finalText, BufferType.SPANNABLE);
}
}
private void applySpacing() {
CharSequence originalText = getText();
if (this != null && originalText != null) {
int i;
StringBuilder builder = new StringBuilder();
for (i = 0; i < originalText.length(); i++) {
builder.append(originalText.charAt(i));
if (i + 1 < originalText.length()) {
builder.append(" ");
}
}
SpannableString finalText = new SpannableString(builder.toString());
if (builder.toString().length() > 1) {
for (i = 1; i < builder.toString().length(); i += 2) {
finalText.setSpan(new ScaleXSpan((this.spacing + 1.0f) / 10.0f), i, i + 1, 33);
}
}
super.setText(finalText, BufferType.SPANNABLE);
}
}
public static void setTextHilighted(TextView textView, String text,SearchElement searchElement) {
textView.setText(text);
if (textView == null
|| TextUtils.isEmpty(text)
|| searchElement ==null) {
return;
}
int startIndex = searchElement.startIndex;
int endIndex = searchElement.endIndex;
if (startIndex < 0 || endIndex > text.length()) {
return;
}
// 开始高亮处理
int color = Color.rgb(69, 192, 26);
textView.setText(text, BufferType.SPANNABLE);
Spannable span = (Spannable) textView.getText();
span.setSpan(new ForegroundColorSpan(color), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
/**
* Sets a description line for the omnibox suggestion.
*
* @param str The description text.
* @param isUrl Whether this text is a URL (as opposed to a normal string).
*/
private void showDescriptionLine(Spannable str, boolean isUrl) {
TextView textLine = mContentsView.mTextLine2;
if (textLine.getVisibility() != VISIBLE) {
textLine.setVisibility(VISIBLE);
}
textLine.setText(str, BufferType.SPANNABLE);
// Force left-to-right rendering for URLs. See UrlBar constructor for details.
if (isUrl) {
textLine.setTextColor(URL_COLOR);
ApiCompatibilityUtils.setTextDirection(textLine, TEXT_DIRECTION_LTR);
} else {
textLine.setTextColor(getStandardFontColor());
ApiCompatibilityUtils.setTextDirection(textLine, TEXT_DIRECTION_INHERIT);
}
}
/**
* Sets a description line for the omnibox suggestion.
*
* @param str The description text.
* @param isUrl Whether this text is a URL (as opposed to a normal string).
*/
private void showDescriptionLine(Spannable str, boolean isUrl) {
TextView textLine = mContentsView.mTextLine2;
if (textLine.getVisibility() != VISIBLE) {
textLine.setVisibility(VISIBLE);
}
textLine.setText(str, BufferType.SPANNABLE);
// Force left-to-right rendering for URLs. See UrlBar constructor for details.
if (isUrl) {
textLine.setTextColor(URL_COLOR);
ApiCompatibilityUtils.setTextDirection(textLine, TEXT_DIRECTION_LTR);
} else {
textLine.setTextColor(getStandardFontColor());
ApiCompatibilityUtils.setTextDirection(textLine, TEXT_DIRECTION_INHERIT);
}
}
@Test
public void textInputValid() {
View root =
rangeDateSelector.onCreateTextInputView(
LayoutInflater.from(context),
null,
null,
new CalendarConstraints.Builder().build(),
new OnSelectionChangedListener<Pair<Long, Long>>() {
@Override
public void onSelectionChanged(Pair<Long, Long> selection) {}
});
TextInputLayout startTextInput = root.findViewById(R.id.mtrl_picker_text_input_range_start);
TextInputLayout endTextInput = root.findViewById(R.id.mtrl_picker_text_input_range_end);
startTextInput.getEditText().setText("2/2/2010", BufferType.EDITABLE);
endTextInput.getEditText().setText("2/2/2012", BufferType.EDITABLE);
assertThat(startTextInput.getError(), nullValue());
assertThat(endTextInput.getError(), nullValue());
}
@Test
public void textInputFormatError() {
View root =
rangeDateSelector.onCreateTextInputView(
LayoutInflater.from(context),
null,
null,
new CalendarConstraints.Builder().build(),
new OnSelectionChangedListener<Pair<Long, Long>>() {
@Override
public void onSelectionChanged(Pair<Long, Long> selection) {}
});
TextInputLayout startTextInput = root.findViewById(R.id.mtrl_picker_text_input_range_start);
TextInputLayout endTextInput = root.findViewById(R.id.mtrl_picker_text_input_range_end);
startTextInput.getEditText().setText("22/22/2010", BufferType.EDITABLE);
endTextInput.getEditText().setText("555-555-5555", BufferType.EDITABLE);
assertThat(startTextInput.getError(), notNullValue());
assertThat(endTextInput.getError(), notNullValue());
}
@Test
public void textInputRangeError() {
rangeDateSelector = new RangeDateSelector();
View root =
rangeDateSelector.onCreateTextInputView(
LayoutInflater.from(context),
null,
null,
new CalendarConstraints.Builder().build(),
new OnSelectionChangedListener<Pair<Long, Long>>() {
@Override
public void onSelectionChanged(Pair<Long, Long> selection) {}
});
TextInputLayout startTextInput = root.findViewById(R.id.mtrl_picker_text_input_range_start);
TextInputLayout endTextInput = root.findViewById(R.id.mtrl_picker_text_input_range_end);
startTextInput.getEditText().setText("2/2/2010", BufferType.EDITABLE);
endTextInput.getEditText().setText("2/2/2008", BufferType.EDITABLE);
assertThat(
startTextInput.getError(),
is((CharSequence) context.getString(R.string.mtrl_picker_invalid_range)));
assertThat(endTextInput.getError(), notNullValue());
}
/**
* Sets a description line for the omnibox suggestion.
*
* @param str The description text.
* @param isUrl Whether this text is a URL (as opposed to a normal string).
*/
private void showDescriptionLine(Spannable str, boolean isUrl) {
TextView textLine = mContentsView.mTextLine2;
if (textLine.getVisibility() != VISIBLE) {
textLine.setVisibility(VISIBLE);
}
textLine.setText(str, BufferType.SPANNABLE);
// Force left-to-right rendering for URLs. See UrlBar constructor for details.
if (isUrl) {
textLine.setTextColor(URL_COLOR);
ApiCompatibilityUtils.setTextDirection(textLine, TEXT_DIRECTION_LTR);
} else {
textLine.setTextColor(getStandardFontColor());
ApiCompatibilityUtils.setTextDirection(textLine, TEXT_DIRECTION_INHERIT);
}
}
public void onServiceConnected(ComponentName className, IBinder service) {
bService = service;
mService = new Messenger(service);
try {
Message msg = Message.obtain(null, MedtronicConstants.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
StringBuffer sb1 = new StringBuffer("");
sb1.append("EXCEPTION!!!!!! "+ e.getMessage()+" "+e.getCause());
for (StackTraceElement st : e.getStackTrace()){
sb1.append(st.toString()).append("\n");
}
Log.e(TAG,"Error Registering Client Service Connection\n"+sb1.toString());
if (ISDEBUG){
display.setText(display.getText()+"Error Registering Client Service Connection\n", BufferType.EDITABLE);
}
// In this case the service has crashed before we could even do anything with it
}
}
public void setRichText(TextView view, String richTextString) {
StringBuilder sb = new StringBuilder();
List<Integer> bolds = new ArrayList<Integer>();
List<Integer> dims = new ArrayList<Integer>();
for (int i = 0; i < richTextString.length(); i++) {
char c = richTextString.charAt(i);
switch (c) {
case '*': bolds.add(sb.length()); break;
case '|': dims.add(sb.length()); break;
default : sb.append(c); break;
}
}
view.setText(sb.toString(), BufferType.SPANNABLE);
Spannable spannable = (Spannable) view.getText();
for (int i = 1; i < bolds.size(); i += 2) {
spannable.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), bolds.get(i-1), bolds.get(i), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
for (int i = 1; i < dims.size(); i += 2) {
spannable.setSpan(new ForegroundColorSpan(0xFF808080), dims.get(i-1), dims.get(i), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
/**
* Add full access condition information about one sector to the layout
* table. (This method will trigger
* {@link #addBlockAC(byte[][], boolean)} and
* {@link #addSectorTrailerAC(byte[][])}
* @param acMatrix Matrix of access conditions bits (C1-C3) where the first
* dimension is the "C" parameter (C1-C3, Index 0-2) and the second
* dimension is the block number
* (Block0-Block2 + Sector Trailer, Index 0-3).
* @param sectorHeader The sector header to display (e.g. "Sector: 0").
* @param hasMoreThan4Blocks True for the last 8 sectors
* of a MIFARE Classic 4K tag.
* @see #addBlockAC(byte[][], boolean)
* @see #addSectorTrailerAC(byte[][])
*/
private void addSectorAC(byte[][] acMatrix, String sectorHeader,
boolean hasMoreThan4Blocks) {
// Add sector header.
TextView header = new TextView(this);
header.setText(Common.colorString(sectorHeader,
getResources().getColor(R.color.blue)),
BufferType.SPANNABLE);
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
tr.addView(header);
mLayout.addView(tr, new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Add Block 0-2.
addBlockAC(acMatrix, hasMoreThan4Blocks);
// Add Sector Trailer.
addSectorTrailerAC(acMatrix);
}
@Override
public void onSetUpView() {
EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
Spannable span = EaseSmileUtils.getSmiledText(context, txtBody.getMessage());
// 设置内容
contentView.setText(span, BufferType.SPANNABLE);
handleTextMessage();
}
public CarlifeDialog setTitleText(String text) {
if (text == null) {
mTitleBar.setVisibility(View.GONE);
mTitleBar.setText("", BufferType.SPANNABLE);
} else {
mTitleBar.setVisibility(View.VISIBLE);
mTitleBar.setText(text, BufferType.SPANNABLE);
}
return this;
}
public CarlifeDialog setFirstBtnText(String text) {
if (text == null) {
mFirstHasText = false;
mFirstBtn.setText("", BufferType.SPANNABLE);
} else {
mFirstHasText = true;
mFirstBtn.setText(text, BufferType.SPANNABLE);
}
setBtnVisible();
return this;
}
public CarlifeDialog setSecondBtnText(String text) {
if (text == null) {
mSecondHasText = false;
mSecondBtn.setText("", BufferType.SPANNABLE);
} else {
mSecondHasText = true;
mSecondBtn.setText(text, BufferType.SPANNABLE);
}
setBtnVisible();
return this;
}
@Override
public void onSetUpView() {
EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
Spannable span = EaseSmileUtils.getSmiledText(context, txtBody.getMessage());
// 设置内容
contentView.setText(span, BufferType.SPANNABLE);
handleTextMessage();
}
/**
* 文本消息
*
* @param message
* @param holder
* @param position
*/
private void handleTextMessage(EMMessage message, ViewHolder holder,
final int position) {
TextMessageBody txtBody = (TextMessageBody) message.getBody();
Spannable span = SmileUtils
.getSmiledText(context, txtBody.getMessage());
// 设置内容
holder.tv.setText(span, BufferType.SPANNABLE);
// 设置长按事件监听
// holder.tv.setOnLongClickListener(new OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
// activity.startActivityForResult((new Intent(activity,
// ContextMenu.class)).putExtra("position", position)
// .putExtra("type", EMMessage.Type.TXT.ordinal()),
// ChatActivity.REQUEST_CODE_CONTEXT_MENU);
// return true;
// }
// });
if (message.direct == EMMessage.Direct.SEND) {
switch (message.status) {
case SUCCESS: // 发送成功
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.GONE);
break;
case FAIL: // 发送失败
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.VISIBLE);
break;
case INPROGRESS: // 发送中
holder.pb.setVisibility(View.VISIBLE);
holder.staus_iv.setVisibility(View.GONE);
break;
default:
// 发送消息
sendMsgInBackground(message, holder);
}
}
}
@Override
public void enableLoadmore(boolean enable) {
if (isEnableLoadmore() == enable) {
return;
}
super.enableLoadmore(enable);
if (!enable) {
// 显示footer
if (mFooterView == null) {
mFooterView = View.inflate(ActivityLifcycleManager.get().current(), LAYOUT_ID_FOOTER, null);
TextView tvEnd = (TextView) mFooterView.findViewById(R.id.txt_end);
tvEnd.setMovementMethod(LinkMovementMethod.getInstance());
String txtEnd = AppUtils.getContext().getString(R.string.to_discover_more_zuthor_and_collection);
SpannableStringBuilder ssb = new SpannableStringBuilder(txtEnd);
int startIndex = txtEnd.indexOf("更");
int endIndex = txtEnd.length();
if (startIndex > -1) {
ssb.setSpan(new ClickableSpanNoUnderLine() {
public void onClick(View widget) {
if (ThrottleUtils.valid(widget)) {
AddSubscribeActivity.launch();
}
}
}, startIndex, endIndex, 0);
tvEnd.setText(ssb, BufferType.SPANNABLE);
}
}
if (mFooterView.getParent() == null) {
addFooterView(mFooterView);
}
} else {
removeFooterView(mFooterView);
}
}
@Override
public void onSetUpView() {
EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
Spannable span = EaseSmileUtils.getSmiledText(context, txtBody.getMessage());
// 设置内容
contentView.setText(span, BufferType.SPANNABLE);
handleTextMessage();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been unexpectedly disconnected - process crashed.
mService = null;
bService = null;
Log.i(TAG,"Service Disconnected\n");
if (ISDEBUG){
display.setText(display.getText()+"Service Disconnected\n", BufferType.EDITABLE);
}
}
/**
* 文本消息
*
* @param message
* @param holder
* @param position
*/
private void handleTextMessage(EMMessage message, ViewHolder holder, final int position) {
TextMessageBody txtBody = (TextMessageBody) message.getBody();
Spannable span = SmileUtils.getSmiledText(context, txtBody.getMessage());
// 设置内容
holder.tv.setText(span, BufferType.SPANNABLE);
// 设置长按事件监听
holder.tv.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
activity.startActivityForResult(
(new Intent(activity, ContextMenu.class)).putExtra("position", position).putExtra("type",
EMMessage.Type.TXT.ordinal()), ChatActivity.REQUEST_CODE_CONTEXT_MENU);
return true;
}
});
if (message.direct == EMMessage.Direct.SEND) {
switch (message.status) {
case SUCCESS: // 发送成功
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.GONE);
break;
case FAIL: // 发送失败
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.VISIBLE);
break;
case INPROGRESS: // 发送中
holder.pb.setVisibility(View.VISIBLE);
holder.staus_iv.setVisibility(View.GONE);
break;
default:
// 发送消息
sendMsgInBackground(message, holder);
}
}
}
public void setHashTag(String hashtagColor, int mhyperlickStatus) {
/*
* Temp color code and undelinestatus used for showing Example
*/
currentHashTagColor = hashtagColor;
tempHyperlinkStatus = mhyperlickStatus;
/*
* Main Section where we set the hash tag for the textview
*/
mHashTagTextView.setText(mTagSelectingTextview.addClickablePart(
Html.fromHtml(testText).toString(), this, mhyperlickStatus, hashtagColor),
BufferType.SPANNABLE);
}
/**
* Add a row with position information to the layout table.
* This row shows the user where the value block is located (sector, block).
* @param value The position information (e.g. "Sector: 1, Block: 2").
*/
private void addPosInfoRow(String value) {
TextView header = new TextView(this);
header.setText(Common.colorString(value,
getResources().getColor(R.color.blue)),
BufferType.SPANNABLE);
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
tr.addView(header);
mLayout.addView(tr, new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
}
public static void setStatus(final TextView textView, final String text) {
final String processedText = PatternsHelper.handleText(text);
textView.setText(Html.fromHtml(processedText), BufferType.SPANNABLE);
LinkifyCompat.addLinks(textView, LinkifyCompat.WEB_URLS);
PatternsHelper.linkifyUsers(textView);
PatternsHelper.linkifyTags(textView);
PatternsHelper.userNameIdMap.clear();
}
public void setText(CharSequence text, BufferType type) {
this.originalText = text;
applySpacing();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessageItem item = messageList.get(position);
ViewHolder holder ;
if(convertView == null){
holder = new ViewHolder();
switch (getItemViewType(position)) {
case LEFT_ITEM:
convertView = infalter.inflate(R.layout.chat_item_left, null);
holder.head = (ImageView) convertView.findViewById(R.id.item_icon);
holder.msg = (TextView) convertView.findViewById(R.id.item_message_textview);
holder.time = (TextView) convertView.findViewById(R.id.item_datetime_textview);
holder.nickname = (TextView) convertView.findViewById(R.id.item_nickname_textview);
holder.progressBar = (ProgressBar) convertView.findViewById(R.id.item_progressbar);
break;
case RIGHT_ITEM:
convertView = infalter.inflate(R.layout.chat_item_right, null);
holder.head = (ImageView) convertView.findViewById(R.id.item_icon);
holder.msg = (TextView) convertView.findViewById(R.id.item_message_textview);
holder.time = (TextView) convertView.findViewById(R.id.item_datetime_textview);
holder.progressBar = (ProgressBar) convertView.findViewById(R.id.item_progressbar);
break;
}
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
if(messageList.get(position).isComMeg()){
holder.nickname.setText(item.getNickName()+":");
}
try{
holder.head.setBackgroundResource(Integer.valueOf(item.getHeadId()));
}catch(Exception e){
e.printStackTrace();
holder.head.setBackgroundResource(R.drawable.head000);
}
holder.time.setText(TimeUtil.getChatTime(item.getTime()));
holder.time.setVisibility(View.VISIBLE);
holder.msg.setText(
convertNormalStringToSpannableString(item.getMessage()),
BufferType.SPANNABLE);
//holder.msg.setText(item.getMessage());
holder.progressBar.setVisibility(View.GONE);
holder.progressBar.setProgress(50);
return convertView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.ease_row_chat_history, parent, false);
}
ViewHolder holder = (ViewHolder) convertView.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.unreadLabel = (TextView) convertView.findViewById(R.id.unread_msg_number);
holder.message = (TextView) convertView.findViewById(R.id.message);
holder.time = (TextView) convertView.findViewById(R.id.time);
holder.avatar = (ImageView) convertView.findViewById(R.id.avatar);
holder.msgState = convertView.findViewById(R.id.msg_state);
holder.list_itease_layout = (RelativeLayout) convertView.findViewById(R.id.list_itease_layout);
convertView.setTag(holder);
}
holder.list_itease_layout.setBackgroundResource(R.drawable.ease_mm_listitem);
// 获取与此用户/群组的会话
EMConversation conversation = getItem(position);
// 获取用户username或者群组groupid
String username = conversation.getUserName();
if (conversation.getType() == EMConversationType.GroupChat) {
// 群聊消息,显示群聊头像
//Glide.with(getContext()).load
holder.avatar.setImageResource(R.drawable.ease_group_icon);
EMGroup group = EMClient.getInstance().groupManager().getGroup(username);
holder.name.setText(group != null ? group.getGroupName() : username);
} else if(conversation.getType() == EMConversationType.ChatRoom){
holder.avatar.setImageResource(R.drawable.ease_group_icon);
EMChatRoom room = EMClient.getInstance().chatroomManager().getChatRoom(username);
holder.name.setText(room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : username);
}else {
EaseUserUtils.setUserAvatar(getContext(), username, holder.avatar);
EaseUserUtils.setUserNick(username, holder.name);
}
if (conversation.getUnreadMsgCount() > 0) {
// 显示与此用户的消息未读数
holder.unreadLabel.setText(String.valueOf(conversation.getUnreadMsgCount()));
holder.unreadLabel.setVisibility(View.VISIBLE);
} else {
holder.unreadLabel.setVisibility(View.INVISIBLE);
}
if (conversation.getAllMsgCount() != 0) {
// 把最后一条消息的内容作为item的message内容
EMMessage lastMessage = conversation.getLastMessage();
holder.message.setText(EaseSmileUtils.getSmiledText(getContext(), EaseCommonUtils.getMessageDigest(lastMessage, (this.getContext()))),
BufferType.SPANNABLE);
holder.time.setText(DateUtils.getTimestampString(new Date(lastMessage.getMsgTime())));
if (lastMessage.direct() == EMMessage.Direct.SEND && lastMessage.status() == EMMessage.Status.FAIL) {
holder.msgState.setVisibility(View.VISIBLE);
} else {
holder.msgState.setVisibility(View.GONE);
}
}
//设置自定义属性
holder.name.setTextColor(primaryColor);
holder.message.setTextColor(secondaryColor);
holder.time.setTextColor(timeColor);
if(primarySize != 0)
holder.name.setTextSize(TypedValue.COMPLEX_UNIT_PX, primarySize);
if(secondarySize != 0)
holder.message.setTextSize(TypedValue.COMPLEX_UNIT_PX, secondarySize);
if(timeSize != 0)
holder.time.setTextSize(TypedValue.COMPLEX_UNIT_PX, timeSize);
return convertView;
}
public CarlifeMessageDialog setMessage(String text) {
mTextView.setText(text, BufferType.SPANNABLE);
return this;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.ease_row_chat_history, parent, false);
}
ViewHolder holder = (ViewHolder) convertView.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.unreadLabel = (TextView) convertView.findViewById(R.id.unread_msg_number);
holder.message = (TextView) convertView.findViewById(R.id.message);
holder.time = (TextView) convertView.findViewById(R.id.time);
holder.avatar = (ImageView) convertView.findViewById(R.id.avatar);
holder.msgState = convertView.findViewById(R.id.msg_state);
holder.list_itease_layout = (RelativeLayout) convertView.findViewById(R.id.list_itease_layout);
convertView.setTag(holder);
}
holder.list_itease_layout.setBackgroundResource(R.drawable.ease_mm_listitem);
// 获取与此用户/群组的会话
EMConversation conversation = getItem(position);
// 获取用户username或者群组groupid
String username = conversation.getUserName();
if (conversation.getType() == EMConversationType.GroupChat) {
// 群聊消息,显示群聊头像
holder.avatar.setImageResource(R.drawable.ease_group_icon);
EMGroup group = EMGroupManager.getInstance().getGroup(username);
holder.name.setText(group != null ? group.getGroupName() : username);
} else if(conversation.getType() == EMConversationType.ChatRoom){
holder.avatar.setImageResource(R.drawable.ease_group_icon);
EMChatRoom room = EMChatManager.getInstance().getChatRoom(username);
holder.name.setText(room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : username);
}else {
EaseUserUtils.setUserAvatar(getContext(), username, holder.avatar);
EaseUserUtils.setUserNick(username, holder.name);
}
if (conversation.getUnreadMsgCount() > 0) {
// 显示与此用户的消息未读数
holder.unreadLabel.setText(String.valueOf(conversation.getUnreadMsgCount()));
holder.unreadLabel.setVisibility(View.VISIBLE);
} else {
holder.unreadLabel.setVisibility(View.INVISIBLE);
}
if (conversation.getMsgCount() != 0) {
// 把最后一条消息的内容作为item的message内容
EMMessage lastMessage = conversation.getLastMessage();
holder.message.setText(EaseSmileUtils.getSmiledText(getContext(), EaseCommonUtils.getMessageDigest(lastMessage, (this.getContext()))),
BufferType.SPANNABLE);
holder.time.setText(DateUtils.getTimestampString(new Date(lastMessage.getMsgTime())));
if (lastMessage.direct == EMMessage.Direct.SEND && lastMessage.status == EMMessage.Status.FAIL) {
holder.msgState.setVisibility(View.VISIBLE);
} else {
holder.msgState.setVisibility(View.GONE);
}
}
//设置自定义属性
holder.name.setTextColor(primaryColor);
holder.message.setTextColor(secondaryColor);
holder.time.setTextColor(timeColor);
if(primarySize != 0)
holder.name.setTextSize(TypedValue.COMPLEX_UNIT_PX, primarySize);
if(secondarySize != 0)
holder.message.setTextSize(TypedValue.COMPLEX_UNIT_PX, secondarySize);
if(timeSize != 0)
holder.time.setTextSize(TypedValue.COMPLEX_UNIT_PX, timeSize);
return convertView;
}