List of usage examples for android.text SpannableStringBuilder setSpan
public void setSpan(Object what, int start, int end, int flags)
From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java
private Spanned getSpannedText(String message) { message = " " + message + " "; SpannableStringBuilder spanned = new SpannableStringBuilder(message); for (Object span : new Object[] { new ForegroundColorSpan(Color.WHITE), new BackgroundColorSpan(Color.parseColor("#88000000")) }) { spanned.setSpan(span, 0, message.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); }/* w w w.j a v a 2 s. c o m*/ return spanned; }
From source file:com.juick.android.MessageMenu.java
protected void runActions() { if (!isDialogMode()) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); final CharSequence[] items = new CharSequence[menuActions.size()]; for (int j = 0; j < items.length; j++) { items[j] = menuActions.get(j).title; }/*www .j a v a 2s .co m*/ builder.setItems(items, this); final AlertDialog alertDialog = builder.create(); alertDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { ColorsTheme.ColorTheme colorTheme = JuickMessagesAdapter.getColorTheme(activity); ColorDrawable divider = new ColorDrawable( colorTheme.getColor(ColorsTheme.ColorKey.COMMON_BACKGROUND, 0xFFFFFFFF)); alertDialog.getListView().setDivider(divider); alertDialog.getListView().setDividerHeight(1); } }); alertDialog.show(); final ListAdapter adapter = alertDialog.getListView().getAdapter(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity); float menuFontScale = 1; try { menuFontScale = Float.parseFloat(sp.getString("menuFontScale", "1.0")); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } final boolean compressedMenu = sp.getBoolean("compressedMenu", false); final boolean singleLineMenu = sp.getBoolean("singleLineMenu", false); final float finalMenuFontScale = menuFontScale; final int screenHeight = activity.getWindow().getWindowManager().getDefaultDisplay().getHeight(); alertDialog.getListView().setAdapter(new ListAdapter() { @Override public boolean areAllItemsEnabled() { return adapter.areAllItemsEnabled(); } @Override public boolean isEnabled(int position) { return adapter.isEnabled(position); } @Override public void registerDataSetObserver(DataSetObserver observer) { adapter.registerDataSetObserver(observer); } @Override public void unregisterDataSetObserver(DataSetObserver observer) { adapter.unregisterDataSetObserver(observer); } @Override public int getCount() { return items.length; } @Override public Object getItem(int position) { return adapter.getItem(position); } @Override public long getItemId(int position) { return adapter.getItemId(position); } @Override public boolean hasStableIds() { return adapter.hasStableIds(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View retval = adapter.getView(position, null, parent); if (retval instanceof TextView) { TextView tv = (TextView) retval; if (compressedMenu) { int minHeight = (int) ((screenHeight * 0.7) / getCount()); tv.setMinHeight(minHeight); tv.setMinimumHeight(minHeight); } if (singleLineMenu) { tv.setSingleLine(true); tv.setEllipsize(TextUtils.TruncateAt.MIDDLE); } tv.setTextSize(22 * finalMenuFontScale); } return retval; } @Override public int getItemViewType(int position) { return adapter.getItemViewType(position); } @Override public int getViewTypeCount() { return adapter.getViewTypeCount(); } @Override public boolean isEmpty() { return adapter.isEmpty(); } }); } else { AlertDialog.Builder builder = new AlertDialog.Builder( new ContextThemeWrapper(activity, R.style.Theme_Sherlock)); View dialogView = activity.getLayoutInflater().inflate(R.layout.message_menu2, null); builder.setView(dialogView); builder.setCancelable(true); int width = activity.getWindowManager().getDefaultDisplay().getWidth(); View scrollView = dialogView.findViewById(R.id.scrollView); scrollView.getLayoutParams().width = (int) (width * 0.90); final AlertDialog alertDialog = builder.create(); alertDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { //MainActivity.restyleChildrenOrWidget(alertDialog.getWindow().getDecorView()); } }); TextView messageNo = (TextView) dialogView.findViewById(R.id.message_no); messageNo.setText(listSelectedItem.getDisplayMessageNo()); Spinner openUrl = (Spinner) dialogView.findViewById(R.id.open_url); Button singleURL = (Button) dialogView.findViewById(R.id.single_url); if (urls != null && urls.size() == 1) { singleURL.setVisibility(View.VISIBLE); openUrl.setVisibility(View.GONE); SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(urls.get(0)); sb.setSpan(new UnderlineSpan(), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); singleURL.setText(sb); singleURL.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); launchURL(listSelectedItem.getMID(), urls.get(0)); } }); } else if (urls != null && urls.size() > 0) { singleURL.setVisibility(View.GONE); openUrl.setVisibility(View.VISIBLE); openUrl.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position != 0) { alertDialog.dismiss(); launchURL(listSelectedItem.getMID(), urls.get(position)); } } @Override public void onNothingSelected(AdapterView<?> parent) { //To change body of implemented methods use File | Settings | File Templates. } }); urls.add(0, activity.getString(R.string.ClickToSelectURL)); openUrl.setAdapter(new BaseAdapter() { @Override public int getCount() { return urls.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = activity.getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null); TextView textView = (TextView) rowView.findViewById(android.R.id.text1); textView.setSingleLine(false); textView.setMaxLines(5); SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(urls.get(position)); if (position == 0) { textView.setTextColor(0xFF808080); } else { sb.setSpan(new UnderlineSpan(), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } textView.setText(sb); return rowView; } }); } else { openUrl.setVisibility(View.GONE); singleURL.setVisibility(View.GONE); } final String UName = listSelectedItem.User.UName; View recommendMessage = dialogView.findViewById(R.id.recommend_message); View deleteMessage = dialogView.findViewById(R.id.delete_message); View saveMessage = dialogView.findViewById(R.id.save_message); View unsaveMessage = dialogView.findViewById(R.id.unsave_message); //View subscribeUser = dialogView.findViewById(R.id.subscribe_user); View subscribeMessage = dialogView.findViewById(R.id.subscribe_message); //View unsubscribeUser = dialogView.findViewById(R.id.unsubscribe_user); View unsubscribeMessage = dialogView.findViewById(R.id.unsubscribe_message); View translateMessage = dialogView.findViewById(R.id.translate_message); View shareMessage = dialogView.findViewById(R.id.share_message); //View blacklistUser = dialogView.findViewById(R.id.blacklist_user); //View filterUser = dialogView.findViewById(R.id.filter_user); //View userBlog = dialogView.findViewById(R.id.user_blog); //View userStats = dialogView.findViewById(R.id.user_stats); View openMessageInBrowser = dialogView.findViewById(R.id.open_message_in_browser); Button userCenter = (Button) dialogView.findViewById(R.id.user_center); if (null == dialogView.findViewById(R.id.column_3)) { // only for portrait userCenter.setText("@" + listSelectedItem.User.UName + " " + userCenter.getText()); } unsubscribeMessage.setEnabled(listSelectedItem.getRID() == 0); subscribeMessage.setEnabled(listSelectedItem.getRID() == 0); unsaveMessage.setEnabled(listSelectedItem.getRID() == 0); recommendMessage.setEnabled(listSelectedItem.getRID() == 0); if (UName.equalsIgnoreCase(JuickAPIAuthorizer.getJuickAccountName(activity.getApplicationContext()))) { recommendMessage.setVisibility(View.GONE); } else { deleteMessage.setVisibility(View.GONE); } if (messagesSource instanceof SavedMessagesSource) { saveMessage.setVisibility(View.GONE); } else { unsaveMessage.setVisibility(View.GONE); } recommendMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); actionRecommendMessage(); } }); deleteMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); actionDeleteMessage(); } }); saveMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); actionSaveMessage(); } }); unsaveMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); actionUnsaveMessage(); } }); // subscribeUser.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // alertDialog.dismiss(); // actionSubscribeUser(); // } // }); subscribeMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); actionSubscribeMessage(); } }); // unsubscribeUser.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // alertDialog.dismiss(); // actionUnsubscribeUser(); // } // }); unsubscribeMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); actionUnsubscribeMessage(); } }); translateMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); actionTranslateMessage(); } }); shareMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); actionShareMessage(); } }); // blacklistUser.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // alertDialog.dismiss(); // actionBlacklistUser(); // } // }); // filterUser.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // alertDialog.dismiss(); // actionFilterUser(UName); // } // }); // userBlog.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // alertDialog.dismiss(); // actionUserBlog(); // } // }); // userStats.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // alertDialog.dismiss(); // actionUserStats(); // } // }); openMessageInBrowser.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); actionOpenMessageInBrowser(); } }); userCenter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); actionUserCenter(); } }); completeInitDialogMode(alertDialog, dialogView); alertDialog.show(); } }
From source file:org.telegram.ui.Cells.DialogCell.java
public void buildLayout() { String nameString = ""; String timeString = ""; String countString = null;/*from ww w .j ava 2 s .com*/ CharSequence messageString = ""; CharSequence printingString = null; if (isDialogCell) { printingString = MessagesController.getInstance().printingStrings.get(currentDialogId); } TextPaint currentNamePaint = namePaint; TextPaint currentMessagePaint = messagePaint; boolean checkMessage = true; drawNameGroup = false; drawNameBroadcast = false; drawNameLock = false; drawNameBot = false; drawVerified = false; if (encryptedChat != null) { drawNameLock = true; nameLockTop = AndroidUtilities.dp(16.5f); if (!LocaleController.isRTL) { nameLockLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline); nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline + 4) + lockDrawable.getIntrinsicWidth(); } else { nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline) - lockDrawable.getIntrinsicWidth(); nameLeft = AndroidUtilities.dp(14); } } else { if (chat != null) { if (chat.id < 0 || ChatObject.isChannel(chat) && !chat.megagroup) { drawNameBroadcast = true; nameLockTop = AndroidUtilities.dp(16.5f); } else { drawNameGroup = true; nameLockTop = AndroidUtilities.dp(17.5f); } drawVerified = chat.verified; if (!LocaleController.isRTL) { nameLockLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline); nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline + 4) + (drawNameGroup ? groupDrawable.getIntrinsicWidth() : broadcastDrawable.getIntrinsicWidth()); } else { nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline) - (drawNameGroup ? groupDrawable.getIntrinsicWidth() : broadcastDrawable.getIntrinsicWidth()); nameLeft = AndroidUtilities.dp(14); } } else { if (!LocaleController.isRTL) { nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline); } else { nameLeft = AndroidUtilities.dp(14); } if (user != null) { if (user.bot) { drawNameBot = true; nameLockTop = AndroidUtilities.dp(16.5f); if (!LocaleController.isRTL) { nameLockLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline); nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline + 4) + botDrawable.getIntrinsicWidth(); } else { nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline) - botDrawable.getIntrinsicWidth(); nameLeft = AndroidUtilities.dp(14); } } drawVerified = user.verified; } } } int lastDate = lastMessageDate; if (lastMessageDate == 0 && message != null) { lastDate = message.messageOwner.date; } if (isDialogCell) { draftMessage = DraftQuery.getDraft(currentDialogId); if (draftMessage != null && (TextUtils.isEmpty(draftMessage.message) && draftMessage.reply_to_msg_id == 0 || lastDate > draftMessage.date && unreadCount != 0) || ChatObject.isChannel(chat) && !chat.megagroup && !chat.creator && !chat.editor || chat != null && (chat.left || chat.kicked)) { draftMessage = null; } } else { draftMessage = null; } if (printingString != null) { lastPrintString = messageString = printingString; currentMessagePaint = messagePrintingPaint; } else { lastPrintString = null; if (draftMessage != null) { checkMessage = false; if (TextUtils.isEmpty(draftMessage.message)) { String draftString = LocaleController.getString("Draft", R.string.Draft); SpannableStringBuilder stringBuilder = SpannableStringBuilder.valueOf(draftString); stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_DRAFT_TEXT_COLOR), 0, draftString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); messageString = stringBuilder; } else { String mess = draftMessage.message; if (mess.length() > 150) { mess = mess.substring(0, 150); } String draftString = LocaleController.getString("Draft", R.string.Draft); SpannableStringBuilder stringBuilder = SpannableStringBuilder .valueOf(String.format("%s: %s", draftString, mess.replace('\n', ' '))); stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_DRAFT_TEXT_COLOR), 0, draftString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); messageString = Emoji.replaceEmoji(stringBuilder, messagePaint.getFontMetricsInt(), AndroidUtilities.dp(20), false); } } else { if (message == null) { if (encryptedChat != null) { currentMessagePaint = messagePrintingPaint; if (encryptedChat instanceof TLRPC.TL_encryptedChatRequested) { messageString = LocaleController.getString("EncryptionProcessing", R.string.EncryptionProcessing); } else if (encryptedChat instanceof TLRPC.TL_encryptedChatWaiting) { if (user != null && user.first_name != null) { messageString = LocaleController.formatString("AwaitingEncryption", R.string.AwaitingEncryption, user.first_name); } else { messageString = LocaleController.formatString("AwaitingEncryption", R.string.AwaitingEncryption, ""); } } else if (encryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) { messageString = LocaleController.getString("EncryptionRejected", R.string.EncryptionRejected); } else if (encryptedChat instanceof TLRPC.TL_encryptedChat) { if (encryptedChat.admin_id == UserConfig.getClientUserId()) { if (user != null && user.first_name != null) { messageString = LocaleController.formatString("EncryptedChatStartedOutgoing", R.string.EncryptedChatStartedOutgoing, user.first_name); } else { messageString = LocaleController.formatString("EncryptedChatStartedOutgoing", R.string.EncryptedChatStartedOutgoing, ""); } } else { messageString = LocaleController.getString("EncryptedChatStartedIncoming", R.string.EncryptedChatStartedIncoming); } } } } else { TLRPC.User fromUser = null; TLRPC.Chat fromChat = null; if (message.isFromUser()) { fromUser = MessagesController.getInstance().getUser(message.messageOwner.from_id); } else { fromChat = MessagesController.getInstance().getChat(message.messageOwner.to_id.channel_id); } if (message.messageOwner instanceof TLRPC.TL_messageService) { messageString = message.messageText; currentMessagePaint = messagePrintingPaint; } else { if (chat != null && chat.id > 0 && fromChat == null) { String name; if (message.isOutOwner()) { name = LocaleController.getString("FromYou", R.string.FromYou); } else if (fromUser != null) { name = UserObject.getFirstName(fromUser).replace("\n", ""); } else if (fromChat != null) { name = fromChat.title.replace("\n", ""); } else { name = "DELETED"; } checkMessage = false; SpannableStringBuilder stringBuilder; if (message.caption != null) { String mess = message.caption.toString(); if (mess.length() > 150) { mess = mess.substring(0, 150); } stringBuilder = SpannableStringBuilder .valueOf(String.format("%s: %s", name, mess.replace('\n', ' '))); } else if (message.messageOwner.media != null && !message.isMediaEmpty()) { currentMessagePaint = messagePrintingPaint; if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) { stringBuilder = SpannableStringBuilder.valueOf(String.format("%s: %s", name, "\uD83C\uDFAE " + message.messageOwner.media.game.title)); } else { stringBuilder = SpannableStringBuilder .valueOf(String.format("%s: %s", name, message.messageText)); } stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_ATTACH_TEXT_COLOR), name.length() + 2, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (message.messageOwner.message != null) { String mess = message.messageOwner.message; if (mess.length() > 150) { mess = mess.substring(0, 150); } stringBuilder = SpannableStringBuilder .valueOf(String.format("%s: %s", name, mess.replace('\n', ' '))); } else { stringBuilder = SpannableStringBuilder.valueOf(""); } if (stringBuilder.length() > 0) { stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_NAME_TEXT_COLOR), 0, name.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } messageString = Emoji.replaceEmoji(stringBuilder, messagePaint.getFontMetricsInt(), AndroidUtilities.dp(20), false); } else { if (message.caption != null) { messageString = message.caption; } else { if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) { messageString = "\uD83C\uDFAE " + message.messageOwner.media.game.title; } else { messageString = message.messageText; } if (message.messageOwner.media != null && !message.isMediaEmpty()) { currentMessagePaint = messagePrintingPaint; } } } } } } } if (draftMessage != null) { timeString = LocaleController.stringForMessageListDate(draftMessage.date); } else if (lastMessageDate != 0) { timeString = LocaleController.stringForMessageListDate(lastMessageDate); } else if (message != null) { timeString = LocaleController.stringForMessageListDate(message.messageOwner.date); } if (message == null) { drawCheck1 = false; drawCheck2 = false; drawClock = false; drawCount = false; drawError = false; } else { if (unreadCount != 0) { drawCount = true; countString = String.format("%d", unreadCount); } else { drawCount = false; } if (message.isOut() && draftMessage == null) { if (message.isSending()) { drawCheck1 = false; drawCheck2 = false; drawClock = true; drawError = false; } else if (message.isSendError()) { drawCheck1 = false; drawCheck2 = false; drawClock = false; drawError = true; drawCount = false; } else if (message.isSent()) { drawCheck1 = !message.isUnread() || ChatObject.isChannel(chat) && !chat.megagroup; drawCheck2 = true; drawClock = false; drawError = false; } } else { drawCheck1 = false; drawCheck2 = false; drawClock = false; drawError = false; } } int timeWidth = (int) Math.ceil(timePaint.measureText(timeString)); timeLayout = new StaticLayout(timeString, timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); if (!LocaleController.isRTL) { timeLeft = getMeasuredWidth() - AndroidUtilities.dp(15) - timeWidth; } else { timeLeft = AndroidUtilities.dp(15); } if (chat != null) { nameString = chat.title; } else if (user != null) { if (user.id == UserConfig.getClientUserId()) { nameString = LocaleController.getString("ChatYourSelfName", R.string.ChatYourSelfName); } else if (user.id / 1000 != 777 && user.id / 1000 != 333 && ContactsController.getInstance().contactsDict.get(user.id) == null) { if (ContactsController.getInstance().contactsDict.size() == 0 && (!ContactsController.getInstance().contactsLoaded || ContactsController.getInstance().isLoadingContacts())) { nameString = UserObject.getUserName(user); } else { if (user.phone != null && user.phone.length() != 0) { nameString = PhoneFormat.getInstance().format("+" + user.phone); } else { nameString = UserObject.getUserName(user); } } } else { nameString = UserObject.getUserName(user); } if (encryptedChat != null) { currentNamePaint = nameEncryptedPaint; } } if (nameString.length() == 0) { nameString = LocaleController.getString("HiddenName", R.string.HiddenName); } int nameWidth; if (!LocaleController.isRTL) { nameWidth = getMeasuredWidth() - nameLeft - AndroidUtilities.dp(14) - timeWidth; } else { nameWidth = getMeasuredWidth() - nameLeft - AndroidUtilities.dp(AndroidUtilities.leftBaseline) - timeWidth; nameLeft += timeWidth; } if (drawNameLock) { nameWidth -= AndroidUtilities.dp(4) + lockDrawable.getIntrinsicWidth(); } else if (drawNameGroup) { nameWidth -= AndroidUtilities.dp(4) + groupDrawable.getIntrinsicWidth(); } else if (drawNameBroadcast) { nameWidth -= AndroidUtilities.dp(4) + broadcastDrawable.getIntrinsicWidth(); } else if (drawNameBot) { nameWidth -= AndroidUtilities.dp(4) + botDrawable.getIntrinsicWidth(); } if (drawClock) { int w = clockDrawable.getIntrinsicWidth() + AndroidUtilities.dp(5); nameWidth -= w; if (!LocaleController.isRTL) { checkDrawLeft = timeLeft - w; } else { checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(5); nameLeft += w; } } else if (drawCheck2) { int w = checkDrawable.getIntrinsicWidth() + AndroidUtilities.dp(5); nameWidth -= w; if (drawCheck1) { nameWidth -= halfCheckDrawable.getIntrinsicWidth() - AndroidUtilities.dp(8); if (!LocaleController.isRTL) { halfCheckDrawLeft = timeLeft - w; checkDrawLeft = halfCheckDrawLeft - AndroidUtilities.dp(5.5f); } else { checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(5); halfCheckDrawLeft = checkDrawLeft + AndroidUtilities.dp(5.5f); nameLeft += w + halfCheckDrawable.getIntrinsicWidth() - AndroidUtilities.dp(8); } } else { if (!LocaleController.isRTL) { checkDrawLeft = timeLeft - w; } else { checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(5); nameLeft += w; } } } if (dialogMuted && !drawVerified) { int w = AndroidUtilities.dp(6) + muteDrawable.getIntrinsicWidth(); nameWidth -= w; if (LocaleController.isRTL) { nameLeft += w; } } else if (drawVerified) { int w = AndroidUtilities.dp(6) + verifiedDrawable.getIntrinsicWidth(); nameWidth -= w; if (LocaleController.isRTL) { nameLeft += w; } } nameWidth = Math.max(AndroidUtilities.dp(12), nameWidth); try { CharSequence nameStringFinal = TextUtils.ellipsize(nameString.replace('\n', ' '), currentNamePaint, nameWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END); nameLayout = new StaticLayout(nameStringFinal, currentNamePaint, nameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } catch (Exception e) { FileLog.e("tmessages", e); } int messageWidth = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline + 16); int avatarLeft; if (!LocaleController.isRTL) { messageLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline); avatarLeft = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 13 : 9); } else { messageLeft = AndroidUtilities.dp(16); avatarLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.isTablet() ? 65 : 61); } avatarImage.setImageCoords(avatarLeft, avatarTop, AndroidUtilities.dp(52), AndroidUtilities.dp(52)); if (drawError) { int w = errorDrawable.getIntrinsicWidth() + AndroidUtilities.dp(8); messageWidth -= w; if (!LocaleController.isRTL) { errorLeft = getMeasuredWidth() - errorDrawable.getIntrinsicWidth() - AndroidUtilities.dp(11); } else { errorLeft = AndroidUtilities.dp(11); messageLeft += w; } } else if (countString != null) { countWidth = Math.max(AndroidUtilities.dp(12), (int) Math.ceil(countPaint.measureText(countString))); countLayout = new StaticLayout(countString, countPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); int w = countWidth + AndroidUtilities.dp(18); messageWidth -= w; if (!LocaleController.isRTL) { countLeft = getMeasuredWidth() - countWidth - AndroidUtilities.dp(19); } else { countLeft = AndroidUtilities.dp(19); messageLeft += w; } drawCount = true; } else { drawCount = false; } if (checkMessage) { if (messageString == null) { messageString = ""; } String mess = messageString.toString(); if (mess.length() > 150) { mess = mess.substring(0, 150); } mess = mess.replace('\n', ' '); messageString = Emoji.replaceEmoji(mess, messagePaint.getFontMetricsInt(), AndroidUtilities.dp(17), false); } messageWidth = Math.max(AndroidUtilities.dp(12), messageWidth); CharSequence messageStringFinal = TextUtils.ellipsize(messageString, currentMessagePaint, messageWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END); try { messageLayout = new StaticLayout(messageStringFinal, currentMessagePaint, messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } catch (Exception e) { FileLog.e("tmessages", e); } double widthpx; float left; if (LocaleController.isRTL) { if (nameLayout != null && nameLayout.getLineCount() > 0) { left = nameLayout.getLineLeft(0); widthpx = Math.ceil(nameLayout.getLineWidth(0)); if (dialogMuted && !drawVerified) { nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - AndroidUtilities.dp(6) - muteDrawable.getIntrinsicWidth()); } else if (drawVerified) { nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - AndroidUtilities.dp(6) - verifiedDrawable.getIntrinsicWidth()); } if (left == 0) { if (widthpx < nameWidth) { nameLeft += (nameWidth - widthpx); } } } if (messageLayout != null && messageLayout.getLineCount() > 0) { left = messageLayout.getLineLeft(0); if (left == 0) { widthpx = Math.ceil(messageLayout.getLineWidth(0)); if (widthpx < messageWidth) { messageLeft += (messageWidth - widthpx); } } } } else { if (nameLayout != null && nameLayout.getLineCount() > 0) { left = nameLayout.getLineRight(0); if (left == nameWidth) { widthpx = Math.ceil(nameLayout.getLineWidth(0)); if (widthpx < nameWidth) { nameLeft -= (nameWidth - widthpx); } } if (dialogMuted || drawVerified) { nameMuteLeft = (int) (nameLeft + left + AndroidUtilities.dp(6)); } } if (messageLayout != null && messageLayout.getLineCount() > 0) { left = messageLayout.getLineRight(0); if (left == messageWidth) { widthpx = Math.ceil(messageLayout.getLineWidth(0)); if (widthpx < messageWidth) { messageLeft -= (messageWidth - widthpx); } } } } }
From source file:org.telegram.ui.ChannelCreateActivity.java
private ChipSpan createAndPutChipForUser(TLRPC.User user) { try {//from w ww.j a v a 2 s . co m LayoutInflater lf = (LayoutInflater) ApplicationLoader.applicationContext .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View textView = lf.inflate(R.layout.group_create_bubble, null); TextView text = (TextView) textView.findViewById(R.id.bubble_text_view); String name = UserObject.getUserName(user); if (name.length() == 0 && user.phone != null && user.phone.length() != 0) { name = PhoneFormat.getInstance().format("+" + user.phone); } text.setText(name + ", "); int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); textView.measure(spec, spec); textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight()); Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(b); canvas.translate(-textView.getScrollX(), -textView.getScrollY()); textView.draw(canvas); textView.setDrawingCacheEnabled(true); Bitmap cacheBmp = textView.getDrawingCache(); Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true); textView.destroyDrawingCache(); final BitmapDrawable bmpDrawable = new BitmapDrawable(b); bmpDrawable.setBounds(0, 0, b.getWidth(), b.getHeight()); SpannableStringBuilder ssb = new SpannableStringBuilder(""); ChipSpan span = new ChipSpan(bmpDrawable, ImageSpan.ALIGN_BASELINE); allSpans.add(span); selectedContacts.put(user.id, span); for (ImageSpan sp : allSpans) { ssb.append("<<"); ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE); } nameTextView.setText(ssb); nameTextView.setSelection(ssb.length()); return span; } catch (Exception e) { FileLog.e("tmessages", e); } return null; }
From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java
private void showMentionsNotification(AccountPreferences pref, long position) { final long accountId = pref.getAccountId(); final Context context = getContext(); final Resources resources = context.getResources(); final NotificationManager nm = getNotificationManager(); final Expression selection; if (pref.isNotificationFollowingOnly()) { selection = Expression.and(Expression.equals(Statuses.ACCOUNT_ID, accountId), Expression.greaterThan(Statuses.STATUS_ID, position), Expression.equals(Statuses.IS_FOLLOWING, 1)); } else {/*from ww w. j a v a 2 s . c o m*/ selection = Expression.and(Expression.equals(Statuses.ACCOUNT_ID, accountId), Expression.greaterThan(Statuses.STATUS_ID, position)); } final String filteredSelection = Utils.buildStatusFilterWhereClause(Mentions.TABLE_NAME, selection) .getSQL(); final String[] userProjection = { Statuses.USER_ID, Statuses.USER_NAME, Statuses.USER_SCREEN_NAME }; final String[] statusProjection = { Statuses.STATUS_ID, Statuses.USER_ID, Statuses.USER_NAME, Statuses.USER_SCREEN_NAME, Statuses.TEXT_UNESCAPED, Statuses.STATUS_TIMESTAMP }; final Cursor statusCursor = mDatabaseWrapper.query(Mentions.TABLE_NAME, statusProjection, filteredSelection, null, null, null, Statuses.SORT_ORDER_TIMESTAMP_DESC); final Cursor userCursor = mDatabaseWrapper.query(Mentions.TABLE_NAME, userProjection, filteredSelection, null, Statuses.USER_ID, null, Statuses.SORT_ORDER_TIMESTAMP_DESC); try { final int usersCount = userCursor.getCount(); final int statusesCount = statusCursor.getCount(); if (statusesCount == 0 || usersCount == 0) return; final String accountName = Utils.getAccountName(context, accountId); final String accountScreenName = Utils.getAccountScreenName(context, accountId); final int idxStatusText = statusCursor.getColumnIndex(Statuses.TEXT_UNESCAPED), idxStatusId = statusCursor.getColumnIndex(Statuses.STATUS_ID), idxStatusTimestamp = statusCursor.getColumnIndex(Statuses.STATUS_TIMESTAMP), idxStatusUserName = statusCursor.getColumnIndex(Statuses.USER_NAME), idxStatusUserScreenName = statusCursor.getColumnIndex(Statuses.USER_SCREEN_NAME), idxUserName = userCursor.getColumnIndex(Statuses.USER_NAME), idxUserScreenName = userCursor.getColumnIndex(Statuses.USER_NAME), idxUserId = userCursor.getColumnIndex(Statuses.USER_NAME); final CharSequence notificationTitle = resources.getQuantityString(R.plurals.N_new_mentions, statusesCount, statusesCount); final String notificationContent; userCursor.moveToFirst(); final String displayName = UserColorNameUtils.getUserNickname(context, userCursor.getLong(idxUserId), mNameFirst ? userCursor.getString(idxUserName) : userCursor.getString(idxUserScreenName)); if (usersCount == 1) { notificationContent = context.getString(R.string.notification_mention, displayName); } else { notificationContent = context.getString(R.string.notification_mention_multiple, displayName, usersCount - 1); } // Add rich notification and get latest tweet timestamp long when = -1, statusId = -1; final InboxStyle style = new InboxStyle(); for (int i = 0, j = Math.min(statusesCount, 5); statusCursor.moveToPosition(i) && i < j; i++) { if (when == -1) { when = statusCursor.getLong(idxStatusTimestamp); } if (statusId == -1) { statusId = statusCursor.getLong(idxStatusId); } final SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(UserColorNameUtils.getUserNickname(context, statusCursor.getLong(idxUserId), mNameFirst ? statusCursor.getString(idxStatusUserName) : statusCursor.getString(idxStatusUserScreenName))); sb.setSpan(new StyleSpan(Typeface.BOLD), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sb.append(' '); sb.append(statusCursor.getString(idxStatusText)); style.addLine(sb); } if (mNameFirst) { style.setSummaryText(accountName); } else { style.setSummaryText("@" + accountScreenName); } // Setup notification final NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setAutoCancel(true); builder.setSmallIcon(R.drawable.ic_stat_mention); builder.setTicker(notificationTitle); builder.setContentTitle(notificationTitle); builder.setContentText(notificationContent); builder.setCategory(NotificationCompat.CATEGORY_SOCIAL); builder.setContentIntent(getContentIntent(context, AUTHORITY_MENTIONS, accountId)); builder.setDeleteIntent(getDeleteIntent(context, AUTHORITY_MENTIONS, accountId, statusId)); builder.setNumber(statusesCount); builder.setWhen(when); builder.setStyle(style); builder.setColor(pref.getNotificationLightColor()); setNotificationPreferences(builder, pref, pref.getMentionsNotificationType()); nm.notify("mentions_" + accountId, NOTIFICATION_ID_MENTIONS_TIMELINE, builder.build()); Utils.sendPebbleNotification(context, notificationContent); } finally { statusCursor.close(); userCursor.close(); } }
From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java
private CharSequence formatMessage(String contact, String body, String contentType) { System.out.println("MessageAdapter.java in formatMessage() "); SpannableStringBuilder buf = new SpannableStringBuilder(); if (!TextUtils.isEmpty(body)) { // Converts html to spannable if ContentType is "text/html". if (contentType != null && "text/html".equals(contentType)) { buf.append("\n"); buf.append(Html.fromHtml(body)); } else {//from w w w. ja v a 2 s.c o m SmileyParser parser = SmileyParser.getInstance(); buf.append(parser.addSmileySpans(body)); } } // We always show two lines because the optional icon bottoms are // aligned with the // bottom of the text field, assuming there are two lines for the // message and the sent time. buf.append("\n"); int startOffset = buf.length(); startOffset = buf.length(); buf.setSpan(mTextSmallSpan, startOffset, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); System.out.println("formatMessage:" + buf); return buf; }
From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java
private void showMessagesNotification(AccountPreferences pref, StringLongPair[] pairs, ContentValues[] valuesArray) {/* w w w . j av a2 s . c om*/ final long accountId = pref.getAccountId(); final long prevOldestId = mReadStateManager.getPosition(TAG_OLDEST_MESSAGES, String.valueOf(accountId)); long oldestId = -1; for (final ContentValues contentValues : valuesArray) { final long messageId = contentValues.getAsLong(DirectMessages.MESSAGE_ID); oldestId = oldestId < 0 ? messageId : Math.min(oldestId, messageId); if (messageId <= prevOldestId) return; } mReadStateManager.setPosition(TAG_OLDEST_MESSAGES, String.valueOf(accountId), oldestId, false); final Context context = getContext(); final Resources resources = context.getResources(); final NotificationManager nm = getNotificationManager(); final ArrayList<Expression> orExpressions = new ArrayList<>(); final String prefix = accountId + "-"; final int prefixLength = prefix.length(); final Set<Long> senderIds = new CompactHashSet<>(); for (StringLongPair pair : pairs) { final String key = pair.getKey(); if (key.startsWith(prefix)) { final long senderId = Long.parseLong(key.substring(prefixLength)); senderIds.add(senderId); final Expression expression = Expression.and(Expression.equals(DirectMessages.SENDER_ID, senderId), Expression.greaterThan(DirectMessages.MESSAGE_ID, pair.getValue())); orExpressions.add(expression); } } orExpressions .add(Expression.notIn(new Column(DirectMessages.SENDER_ID), new RawItemArray(senderIds.toArray()))); final Expression selection = Expression.and(Expression.equals(DirectMessages.ACCOUNT_ID, accountId), Expression.greaterThan(DirectMessages.MESSAGE_ID, prevOldestId), Expression.or(orExpressions.toArray(new Expression[orExpressions.size()]))); final String filteredSelection = selection.getSQL(); final String[] userProjection = { DirectMessages.SENDER_ID, DirectMessages.SENDER_NAME, DirectMessages.SENDER_SCREEN_NAME }; final String[] messageProjection = { DirectMessages.MESSAGE_ID, DirectMessages.SENDER_ID, DirectMessages.SENDER_NAME, DirectMessages.SENDER_SCREEN_NAME, DirectMessages.TEXT_UNESCAPED, DirectMessages.MESSAGE_TIMESTAMP }; final Cursor messageCursor = mDatabaseWrapper.query(DirectMessages.Inbox.TABLE_NAME, messageProjection, filteredSelection, null, null, null, DirectMessages.DEFAULT_SORT_ORDER); final Cursor userCursor = mDatabaseWrapper.query(DirectMessages.Inbox.TABLE_NAME, userProjection, filteredSelection, null, DirectMessages.SENDER_ID, null, DirectMessages.DEFAULT_SORT_ORDER); try { final int usersCount = userCursor.getCount(); final int messagesCount = messageCursor.getCount(); if (messagesCount == 0 || usersCount == 0) return; final String accountName = Utils.getAccountName(context, accountId); final String accountScreenName = Utils.getAccountScreenName(context, accountId); final int idxMessageText = messageCursor.getColumnIndex(DirectMessages.TEXT_UNESCAPED), idxMessageTimestamp = messageCursor.getColumnIndex(DirectMessages.MESSAGE_TIMESTAMP), idxMessageId = messageCursor.getColumnIndex(DirectMessages.MESSAGE_ID), idxMessageUserId = messageCursor.getColumnIndex(DirectMessages.SENDER_ID), idxMessageUserName = messageCursor.getColumnIndex(DirectMessages.SENDER_NAME), idxMessageUserScreenName = messageCursor.getColumnIndex(DirectMessages.SENDER_SCREEN_NAME), idxUserName = userCursor.getColumnIndex(DirectMessages.SENDER_NAME), idxUserScreenName = userCursor.getColumnIndex(DirectMessages.SENDER_NAME), idxUserId = userCursor.getColumnIndex(DirectMessages.SENDER_NAME); final CharSequence notificationTitle = resources.getQuantityString(R.plurals.N_new_messages, messagesCount, messagesCount); final String notificationContent; userCursor.moveToFirst(); final String displayName = UserColorNameUtils.getUserNickname(context, userCursor.getLong(idxUserId), mNameFirst ? userCursor.getString(idxUserName) : userCursor.getString(idxUserScreenName)); if (usersCount == 1) { if (messagesCount == 1) { notificationContent = context.getString(R.string.notification_direct_message, displayName); } else { notificationContent = context.getString(R.string.notification_direct_message_multiple_messages, displayName, messagesCount); } } else { notificationContent = context.getString(R.string.notification_direct_message_multiple_users, displayName, usersCount - 1, messagesCount); } final LongSparseArray<Long> idsMap = new LongSparseArray<>(); // Add rich notification and get latest tweet timestamp long when = -1; final InboxStyle style = new InboxStyle(); for (int i = 0; messageCursor.moveToPosition(i) && i < messagesCount; i++) { if (when < 0) { when = messageCursor.getLong(idxMessageTimestamp); } if (i < 5) { final SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(UserColorNameUtils.getUserNickname(context, messageCursor.getLong(idxUserId), mNameFirst ? messageCursor.getString(idxMessageUserName) : messageCursor.getString(idxMessageUserScreenName))); sb.setSpan(new StyleSpan(Typeface.BOLD), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sb.append(' '); sb.append(messageCursor.getString(idxMessageText)); style.addLine(sb); } final long userId = messageCursor.getLong(idxMessageUserId); final long messageId = messageCursor.getLong(idxMessageId); idsMap.put(userId, Math.max(idsMap.get(userId, -1L), messageId)); } if (mNameFirst) { style.setSummaryText(accountName); } else { style.setSummaryText("@" + accountScreenName); } final StringLongPair[] positions = new StringLongPair[idsMap.size()]; for (int i = 0, j = idsMap.size(); i < j; i++) { positions[i] = new StringLongPair(String.valueOf(idsMap.keyAt(i)), idsMap.valueAt(i)); } // Setup notification final NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setAutoCancel(true); builder.setSmallIcon(R.drawable.ic_stat_direct_message); builder.setTicker(notificationTitle); builder.setContentTitle(notificationTitle); builder.setContentText(notificationContent); builder.setCategory(NotificationCompat.CATEGORY_SOCIAL); builder.setContentIntent(getContentIntent(context, AUTHORITY_DIRECT_MESSAGES, accountId)); builder.setContentIntent(getDeleteIntent(context, AUTHORITY_DIRECT_MESSAGES, accountId, positions)); builder.setNumber(messagesCount); builder.setWhen(when); builder.setStyle(style); builder.setColor(pref.getNotificationLightColor()); setNotificationPreferences(builder, pref, pref.getDirectMessagesNotificationType()); nm.notify("messages_" + accountId, NOTIFICATION_ID_DIRECT_MESSAGES, builder.build()); Utils.sendPebbleNotification(context, notificationContent); } finally { messageCursor.close(); userCursor.close(); } }
From source file:cgeo.geocaching.CacheDetailActivity.java
static void appendClickableList(final SpannableStringBuilder builder, final View view, final Integer listId) { final int start = builder.length(); builder.append(DataStore.getList(listId).getTitle()); builder.setSpan(new ClickableSpan() { @Override//from ww w .j a v a 2 s .c o m public void onClick(final View widget) { Settings.setLastDisplayedList(listId); CacheListActivity.startActivityOffline(view.getContext()); } }, start, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); }
From source file:com.android.mail.browse.ConversationItemView.java
private void layoutParticipantText(SpannableStringBuilder participantText) { if (participantText != null) { if (isActivated() && showActivatedText()) { participantText.setSpan(sActivatedTextSpan, 0, mHeader.styledMessageInfoStringOffset, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else {//from w w w. jav a 2s . co m participantText.removeSpan(sActivatedTextSpan); } final int w = mSendersWidth; final int h = mCoordinates.sendersHeight; mSendersTextView.setLayoutParams(new ViewGroup.LayoutParams(w, h)); mSendersTextView.setMaxLines(mCoordinates.sendersLineCount); mSendersTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mCoordinates.sendersFontSize); layoutViewExactly(mSendersTextView, w, h); mSendersTextView.setText(participantText); } }
From source file:android.support.v7.widget.SearchView.java
private CharSequence getDecoratedHint(CharSequence hintText) { // If the field is always expanded or we don't have a search hint icon, // then don't add the search icon to the hint. if (!mIconifiedByDefault || mSearchHintIcon == null) { return hintText; }//w ww . ja va2 s.co m final int textSize = (int) (mSearchSrcTextView.getTextSize() * 1.25); mSearchHintIcon.setBounds(0, 0, textSize, textSize); final SpannableStringBuilder ssb = new SpannableStringBuilder(" "); ssb.setSpan(new ImageSpan(mSearchHintIcon), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.append(hintText); return ssb; }