List of usage examples for android.text SpannableStringBuilder length
public int length()
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 {/* w ww . j a v a 2 s .co 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.ferdi2005.secondgram.AndroidUtilities.java
public static CharSequence generateSearchName(String name, String name2, String q) { if (name == null && name2 == null) { return ""; }// ww w . j ava2 s.c o m SpannableStringBuilder builder = new SpannableStringBuilder(); String wholeString = name; if (wholeString == null || wholeString.length() == 0) { wholeString = name2; } else if (name2 != null && name2.length() != 0) { wholeString += " " + name2; } wholeString = wholeString.trim(); String lower = " " + wholeString.toLowerCase(); int index; int lastIndex = 0; while ((index = lower.indexOf(" " + q, lastIndex)) != -1) { int idx = index - (index == 0 ? 0 : 1); int end = q.length() + (index == 0 ? 0 : 1) + idx; if (lastIndex != 0 && lastIndex != idx + 1) { builder.append(wholeString.substring(lastIndex, idx)); } else if (lastIndex == 0 && idx != 0) { builder.append(wholeString.substring(0, idx)); } String query = wholeString.substring(idx, Math.min(wholeString.length(), end)); if (query.startsWith(" ")) { builder.append(" "); } query = query.trim(); int start = builder.length(); builder.append(query); builder.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText4)), start, start + query.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); lastIndex = end; } if (lastIndex != -1 && lastIndex != wholeString.length()) { builder.append(wholeString.substring(lastIndex, wholeString.length())); } return builder; }
From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java
private void showMessagesNotification(AccountPreferences pref, StringLongPair[] pairs, ContentValues[] valuesArray) {//from ww w .ja v a 2 s . c o m 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:com.amazon.android.ui.widget.EllipsizedTextView.java
/** * Sets ellipsis properties.// w ww .j a v a2 s .c o m * * @param widthMeasureSpec Ellipsis width. * @param heightMeasureSpec Ellipsis height. * @param layout Layout for ellipsis. * @param lastLine Last line length for ellipsis. * @param maxLines Max lines in ellipsis. */ private void setEllipsis(int widthMeasureSpec, int heightMeasureSpec, Layout layout, int lastLine, int maxLines) { mIsEllipsized = true; setFocusable(true); setClickable(true); final SpannableString ss = new SpannableString(mCharSequence); String visibleText = mCharSequence.toString(); mEllipsisImage = new StateImageSpan(getContext(), mGuillemetDrawableId, ImageSpan.ALIGN_BASELINE); final SpannableStringBuilder spannedText = new SpannableStringBuilder(); int ellipsisIndex = layout.getLineStart(Math.min(lastLine + 1, maxLines)); // Keep chopping words off until the ellipsis is on a visible line or there is only one // line left. do { // Only truncate the last line for long description. if (lastLine >= maxLines) { // Getting the first word break index before the last index of maxline. int safeBreakIndex = breakBefore(visibleText, ellipsisIndex, BreakIterator.getWordInstance()); final int maxLineStart = layout.getLineStart(maxLines - 1); // If this check pass, it means we just truncated a word that is longer than a line. if (safeBreakIndex < maxLineStart) { // Need to check character by character and break in the middle now. Checking // word by word should cover most cases, only do this if a word is longer than // line width. safeBreakIndex = breakBefore(visibleText, ellipsisIndex, BreakIterator.getCharacterInstance()); } ellipsisIndex = safeBreakIndex; } visibleText = visibleText.substring(0, ellipsisIndex); final CharSequence charOutput = ss.subSequence(0, ellipsisIndex); // Re-add ellipsis and convert to image spannedText.replace(0, spannedText.length(), charOutput); spannedText.append(ELLIPSIS); spannedText.setSpan(mEllipsisImage, ellipsisIndex, ellipsisIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE); // Reset text and re-measure. super.setText(spannedText, BufferType.SPANNABLE); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } while (getLineCount() > getMaxLines() && getLineCount() > 1); requestFocus(); }
From source file:org.getlantern.firetweet.fragment.support.UserFragment.java
private void updateTitleColor() { final int[] location = new int[2]; mNameView.getLocationOnScreen(location); final float nameShowingRatio = (mHeaderDrawerLayout.getPaddingTop() - location[1]) / (float) mNameView.getHeight(); final int textAlpha = Math.round(0xFF * MathUtils.clamp(nameShowingRatio, 0, 1)); final FragmentActivity activity = getActivity(); final SpannableStringBuilder spannedTitle; final CharSequence title = activity.getTitle(); if (title instanceof SpannableStringBuilder) { spannedTitle = (SpannableStringBuilder) title; } else {//www .j a va 2 s . c o m spannedTitle = SpannableStringBuilder.valueOf(title); } final TextAlphaSpan[] spans = spannedTitle.getSpans(0, spannedTitle.length(), TextAlphaSpan.class); if (spans.length > 0) { spans[0].setAlpha(textAlpha); } else { spannedTitle.setSpan(new TextAlphaSpan(textAlpha), 0, spannedTitle.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } activity.setTitle(spannedTitle); }
From source file:net.zionsoft.obadiah.ui.adapters.TranslationListAdapter.java
public void setTranslations(@Nullable List<TranslationInfo> downloaded, @Nullable List<TranslationInfo> available) { mSectionHeaders.clear();/*w w w. j ava2 s . c o m*/ mTranslations.clear(); mCount = 0; if (downloaded != null && downloaded.size() > 0) { final List<TranslationInfoHolder> translations = new ArrayList<TranslationInfoHolder>( downloaded.size()); for (TranslationInfo translationInfo : downloaded) { final SpannableStringBuilder text = new SpannableStringBuilder(translationInfo.name); text.setSpan(mMediumSizeSpan, 0, translationInfo.name.length(), 0); translations.add(new TranslationInfoHolder(translationInfo, text, true)); } mSectionHeaders.add(mDownloadedTranslationsTitle); mTranslations.add(translations); mCount = downloaded.size() + 1; } if (available != null) { for (TranslationInfo translationInfo : available) { final String language = new Locale(translationInfo.language.split("_")[0]).getDisplayLanguage(); int index = 0; List<TranslationInfoHolder> translations = null; for (String sectionHeader : mSectionHeaders) { if (sectionHeader.equals(language)) { translations = mTranslations.get(index); break; } ++index; } if (translations == null) { translations = new ArrayList<TranslationInfoHolder>(); mSectionHeaders.add(language); mTranslations.add(translations); ++mCount; } final SpannableStringBuilder text = new SpannableStringBuilder( mResources.getString(R.string.text_available_translation_info, translationInfo.name, translationInfo.size / 1024)); text.setSpan(mMediumSizeSpan, 0, translationInfo.name.length(), 0); text.setSpan(mSmallSizeSpan, translationInfo.name.length(), text.length(), 0); translations.add(new TranslationInfoHolder(translationInfo, text, false)); ++mCount; } } }
From source file:com.android.mail.browse.ConversationItemView.java
SpannableStringBuilder elideParticipants(List<SpannableString> parts) { final SpannableStringBuilder builder = new SpannableStringBuilder(); float totalWidth = 0; boolean ellipsize = false; float width;//from ww w .j a v a 2 s .c o m boolean skipToHeader = false; // start with "To: " if we're showing recipients if (mDisplayedFolder.shouldShowRecipients() && !parts.isEmpty()) { final SpannableString toHeader = SendersView.getFormattedToHeader(); CharacterStyle[] spans = toHeader.getSpans(0, toHeader.length(), CharacterStyle.class); // There is only 1 character style span; make sure we apply all the // styles to the paint object before measuring. if (spans.length > 0) { spans[0].updateDrawState(sPaint); } totalWidth += sPaint.measureText(toHeader.toString()); builder.append(toHeader); skipToHeader = true; } final SpannableStringBuilder messageInfoString = mHeader.messageInfoString; if (!TextUtils.isEmpty(messageInfoString)) { CharacterStyle[] spans = messageInfoString.getSpans(0, messageInfoString.length(), CharacterStyle.class); // There is only 1 character style span; make sure we apply all the // styles to the paint object before measuring. if (spans.length > 0) { spans[0].updateDrawState(sPaint); } // Paint the message info string to see if we lose space. float messageInfoWidth = sPaint.measureText(messageInfoString.toString()); totalWidth += messageInfoWidth; } SpannableString prevSender = null; SpannableString ellipsizedText; for (SpannableString sender : parts) { // There may be null sender strings if there were dupes we had to remove. if (sender == null) { continue; } // No more width available, we'll only show fixed fragments. if (ellipsize) { break; } CharacterStyle[] spans = sender.getSpans(0, sender.length(), CharacterStyle.class); // There is only 1 character style span. if (spans.length > 0) { spans[0].updateDrawState(sPaint); } // If there are already senders present in this string, we need to // make sure we prepend the dividing token if (SendersView.sElidedString.equals(sender.toString())) { sender = copyStyles(spans, sElidedPaddingToken + sender + sElidedPaddingToken); } else if (!skipToHeader && builder.length() > 0 && (prevSender == null || !SendersView.sElidedString.equals(prevSender.toString()))) { sender = copyStyles(spans, sSendersSplitToken + sender); } else { skipToHeader = false; } prevSender = sender; if (spans.length > 0) { spans[0].updateDrawState(sPaint); } // Measure the width of the current sender and make sure we have space width = (int) sPaint.measureText(sender.toString()); if (width + totalWidth > mSendersWidth) { // The text is too long, new line won't help. We have to // ellipsize text. ellipsize = true; width = mSendersWidth - totalWidth; // ellipsis width? ellipsizedText = copyStyles(spans, TextUtils.ellipsize(sender, sPaint, width, TruncateAt.END)); width = (int) sPaint.measureText(ellipsizedText.toString()); } else { ellipsizedText = null; } totalWidth += width; final CharSequence fragmentDisplayText; if (ellipsizedText != null) { fragmentDisplayText = ellipsizedText; } else { fragmentDisplayText = sender; } builder.append(fragmentDisplayText); } mHeader.styledMessageInfoStringOffset = builder.length(); if (!TextUtils.isEmpty(messageInfoString)) { builder.append(messageInfoString); } return builder; }
From source file:com.csipsimple.ui.incall.CallActivity.java
/** * Controls buttons (accept, reject etc). * @param whichAction what action has been done * @param call//from www .j a v a 2 s . com */ @Override public void onTrigger(int whichAction, final SipCallSession call) { // Sanity check for actions requiring valid call id if (whichAction == TAKE_CALL || whichAction == REJECT_CALL || whichAction == DONT_TAKE_CALL || whichAction == TERMINATE_CALL || whichAction == DETAILED_DISPLAY || whichAction == TOGGLE_HOLD || whichAction == START_RECORDING || whichAction == STOP_RECORDING || whichAction == DTMF_DISPLAY || whichAction == XFER_CALL || whichAction == TRANSFER_CALL || whichAction == START_VIDEO || whichAction == STOP_VIDEO) { // We check that current call is valid for any actions if (call == null) { Log.e(TAG, "Try to do an action on a null call !!!"); return; } if (call.getCallId() == SipCallSession.INVALID_CALL_ID) { Log.e(TAG, "Try to do an action on an invalid call !!!"); return; } } // Reset proximity sensor timer proximityManager.restartTimer(); try { switch (whichAction) { case TAKE_CALL: { if (service != null) { Log.i(TAG, "Answering call " + call.getCallId()); boolean shouldHoldOthers = false; // Well actually we should be always before confirmed if (call.isBeforeConfirmed()) { shouldHoldOthers = true; } service.answer(call.getCallId(), StatusCode.OK); // if it's a ringing call, we assume that user wants to // hold other calls if (shouldHoldOthers && callsInfo != null) { for (SipCallSession callInfo : callsInfo) { // For each active and running call if (SipCallSession.InvState.CONFIRMED == callInfo.getCallState() && !callInfo.isLocalHeld() && callInfo.getCallId() != call.getCallId()) { Log.d(TAG, "Hold call " + callInfo.getCallId()); service.hold(callInfo.getCallId()); } } } } break; } case DONT_TAKE_CALL: { if (service != null) { Log.i(TAG, "Rejecting the call with BUSY_HERE"); service.hangup(call.getCallId(), StatusCode.BUSY_HERE); } break; } case REJECT_CALL: if (service != null) { Log.i(TAG, "Rejecting the call"); service.hangup(call.getCallId(), 0); } break; case TERMINATE_CALL: { if (service != null) { Log.i(TAG, "Terminating the call"); service.hangup(call.getCallId(), 0); } break; } case CANCEL_CALL: { if (service != null) { Log.i(TAG, "Cancelling the call"); service.hangup(call.getCallId(), 0); } sendCancelCallBroadcast(); break; } case MUTE_ON: case MUTE_OFF: { if (service != null) { Log.i(TAG, "Set mute " + (whichAction == MUTE_ON)); service.setMicrophoneMute((whichAction == MUTE_ON) ? true : false); } break; } case SPEAKER_ON: case SPEAKER_OFF: { if (service != null) { Log.d(TAG, "Set speaker " + (whichAction == SPEAKER_ON)); useAutoDetectSpeaker = false; service.setSpeakerphoneOn((whichAction == SPEAKER_ON) ? true : false); } break; } case BLUETOOTH_ON: case BLUETOOTH_OFF: { if (service != null) { Log.d(TAG, "Set bluetooth " + (whichAction == BLUETOOTH_ON)); service.setBluetoothOn((whichAction == BLUETOOTH_ON) ? true : false); } break; } case DTMF_DISPLAY: { Log.d(TAG, "DTMF_DISPLAY"); showDialpad(call.getCallId()); break; } case DETAILED_DISPLAY: { if (service != null) { if (infoDialog != null) { infoDialog.dismiss(); } String infos = service.showCallInfosDialog(call.getCallId()); String natType = service.getLocalNatType(); SpannableStringBuilder buf = new SpannableStringBuilder(); Builder builder = new Builder(this); buf.append(infos); if (!TextUtils.isEmpty(natType)) { buf.append("\r\nLocal NAT type detected : "); buf.append(natType); } TextAppearanceSpan textSmallSpan = new TextAppearanceSpan(this, android.R.style.TextAppearance_Small); buf.setSpan(textSmallSpan, 0, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); infoDialog = builder.setIcon(android.R.drawable.ic_dialog_info).setMessage(buf) .setNeutralButton(R.string.ok, null).create(); infoDialog.show(); } break; } case TOGGLE_HOLD: { if (service != null) { // Log.d(TAG, // "Current state is : "+callInfo.getCallState().name()+" / "+callInfo.getMediaStatus().name()); if (call.getMediaStatus() == SipCallSession.MediaState.LOCAL_HOLD || call.getMediaStatus() == SipCallSession.MediaState.NONE) { service.reinvite(call.getCallId(), true); } else { service.hold(call.getCallId()); } } break; } case MEDIA_SETTINGS: { startActivity(new Intent(this, InCallMediaControl.class)); break; } case XFER_CALL: { Intent pickupIntent = new Intent(this, PickupSipUri.class); pickupIntent.putExtra(CALL_ID, call.getCallId()); startActivityForResult(pickupIntent, PICKUP_SIP_URI_XFER); break; } case TRANSFER_CALL: { final ArrayList<SipCallSession> remoteCalls = new ArrayList<SipCallSession>(); if (callsInfo != null) { for (SipCallSession remoteCall : callsInfo) { // Verify not current call if (remoteCall.getCallId() != call.getCallId() && remoteCall.isOngoing()) { remoteCalls.add(remoteCall); } } } if (remoteCalls.size() > 0) { Builder builder = new Builder(this); CharSequence[] simpleAdapter = new String[remoteCalls.size()]; for (int i = 0; i < remoteCalls.size(); i++) { simpleAdapter[i] = remoteCalls.get(i).getRemoteContact(); } builder.setSingleChoiceItems(simpleAdapter, -1, new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (service != null) { try { // 1 = PJSUA_XFER_NO_REQUIRE_REPLACES service.xferReplace(call.getCallId(), remoteCalls.get(which).getCallId(), 1); } catch (RemoteException e) { Log.e(TAG, "Was not able to call service method", e); } } dialog.dismiss(); } }).setCancelable(true).setNeutralButton(R.string.cancel, new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } break; } case ADD_CALL: { Intent pickupIntent = new Intent(this, PickupSipUri.class); startActivityForResult(pickupIntent, PICKUP_SIP_URI_NEW_CALL); break; } case START_RECORDING: { if (service != null) { // TODO : add a tweaky setting for two channel recording in different files. // Would just result here in two calls to start recording with different bitmask service.startRecording(call.getCallId(), SipManager.BITMASK_ALL); } break; } case STOP_RECORDING: { if (service != null) { service.stopRecording(call.getCallId()); } break; } case START_VIDEO: case STOP_VIDEO: { if (service != null) { Bundle opts = new Bundle(); opts.putBoolean(SipCallSession.OPT_CALL_VIDEO, whichAction == START_VIDEO); service.updateCallOptions(call.getCallId(), opts); } break; } case ZRTP_TRUST: { if (service != null) { service.zrtpSASVerified(call.getCallId()); } break; } case ZRTP_REVOKE: { if (service != null) { service.zrtpSASRevoke(call.getCallId()); } break; } } } catch (RemoteException e) { Log.e(TAG, "Was not able to call service method", e); } }
From source file:com.newcell.calltext.ui.messages.ConversationsAdapter.java
private CharSequence formatMessage(Cursor cursor) { SpannableStringBuilder buf = new SpannableStringBuilder(); /*/*from ww w.j a va 2 s. com*/ String remoteContact = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_FROM)); Log.i(TAG, "remoteContact: '" + remoteContact + "'"); if (remoteContact.equals("SELF")) { remoteContact = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_TO)); // buf.append("To: "); } */ String remoteContactFull = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_FROM_FULL)); Log.i(TAG, "RemoteContactFull::" + remoteContactFull); /* String newRemoteContact = SipUri.getPhoneNumberFromApiSipString(remoteContactFull); if(newRemoteContact != "") { remoteContactFull = newRemoteContact; remoteContactFull = "\"" + remoteContactFull + "\" <sip:" + remoteContactFull + "@" + SipManager.SERVER_DOMAIN + ">"; Log.i(TAG, "New remoteContactFull::" + remoteContactFull); } */ CallerInfo callerInfo = CallerInfo.getCallerInfoFromSipUri(mContext, remoteContactFull); //Log.i(TAG, "CallerInfo.number: '" + callerInfo.phoneNumber + "'"); if (callerInfo != null && callerInfo.contactExists) { buf.append(callerInfo.name); /* * 6/19/2014 Removed the addition of the phone number to the title when the recipient is a contact */ //buf.append(" / "); //buf.append(SipUri.getDisplayedSimpleContact(remoteContactFull)); } else { buf.append(SipUri.getDisplayedSimpleContact(remoteContactFull)); } int counter = cursor.getInt(cursor.getColumnIndex("counter")); if (counter > 1) { buf.append(" (" + counter + ") "); } int read = cursor.getInt(cursor.getColumnIndex(SipMessage.FIELD_READ)); // Unread messages are shown in bold if (read == 0) { buf.setSpan(STYLE_BOLD, 0, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } return buf; }
From source file:org.telegram.ui.ChannelCreateActivity.java
@Override public View createView(Context context) { searching = false;/*from w w w . ja va 2s . c om*/ searchWas = false; actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(true); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == done_button) { if (currentStep == 0) { if (donePressed) { return; } if (nameTextView.length() == 0) { Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); if (v != null) { v.vibrate(200); } AndroidUtilities.shakeView(nameTextView, 2, 0); return; } donePressed = true; if (avatarUpdater.uploadingAvatar != null) { createAfterUpload = true; progressDialog = new ProgressDialog(getParentActivity()); progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCancelable(false); progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { createAfterUpload = false; progressDialog = null; donePressed = false; try { dialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); progressDialog.show(); return; } final int reqId = MessagesController.getInstance().createChat( nameTextView.getText().toString(), new ArrayList<Integer>(), descriptionTextView.getText().toString(), ChatObject.CHAT_TYPE_CHANNEL, ChannelCreateActivity.this); progressDialog = new ProgressDialog(getParentActivity()); progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCancelable(false); progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ConnectionsManager.getInstance().cancelRequest(reqId, true); donePressed = false; try { dialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); progressDialog.show(); } else if (currentStep == 1) { if (!isPrivate) { if (nameTextView.length() == 0) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("ChannelPublicEmptyUsername", R.string.ChannelPublicEmptyUsername)); builder.setPositiveButton(LocaleController.getString("Close", R.string.Close), null); showDialog(builder.create()); return; } else { if (!lastNameAvailable) { Vibrator v = (Vibrator) getParentActivity() .getSystemService(Context.VIBRATOR_SERVICE); if (v != null) { v.vibrate(200); } AndroidUtilities.shakeView(checkTextView, 2, 0); return; } else { MessagesController.getInstance().updateChannelUserName(chatId, lastCheckName); } } } Bundle args = new Bundle(); args.putInt("step", 2); args.putInt("chat_id", chatId); presentFragment(new ChannelCreateActivity(args), true); } else { ArrayList<TLRPC.InputUser> result = new ArrayList<>(); for (Integer uid : selectedContacts.keySet()) { TLRPC.InputUser user = MessagesController .getInputUser(MessagesController.getInstance().getUser(uid)); if (user != null) { result.add(user); } } MessagesController.getInstance().addUsersToChannel(chatId, result, null); NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); Bundle args2 = new Bundle(); args2.putInt("chat_id", chatId); presentFragment(new ChatActivity(args2), true); } } } }); ActionBarMenu menu = actionBar.createMenu(); doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); if (currentStep != 2) { fragmentView = new ScrollView(context); ScrollView scrollView = (ScrollView) fragmentView; scrollView.setFillViewport(true); linearLayout = new LinearLayout(context); scrollView.addView(linearLayout, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } else { fragmentView = new LinearLayout(context); fragmentView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); linearLayout = (LinearLayout) fragmentView; } linearLayout.setOrientation(LinearLayout.VERTICAL); if (currentStep == 0) { actionBar.setTitle(LocaleController.getString("NewChannel", R.string.NewChannel)); fragmentView.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background)); FrameLayout frameLayout = new FrameLayout(context); linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); avatarImage = new BackupImageView(context); avatarImage.setRoundRadius(AndroidUtilities.dp(32)); avatarDrawable.setInfo(5, null, null, false); avatarDrawable.setDrawPhoto(true); avatarImage.setImageDrawable(avatarDrawable); frameLayout.addView(avatarImage, LayoutHelper.createFrame(64, 64, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 16, 12, LocaleController.isRTL ? 16 : 0, 12)); avatarImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); CharSequence[] items; if (avatar != null) { items = new CharSequence[] { LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto) }; } else { items = new CharSequence[] { LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley) }; } builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0) { avatarUpdater.openCamera(); } else if (i == 1) { avatarUpdater.openGallery(); } else if (i == 2) { avatar = null; uploadedAvatar = null; avatarImage.setImage(avatar, "50_50", avatarDrawable); } } }); showDialog(builder.create()); } }); nameTextView = new EditText(context); nameTextView.setHint(LocaleController.getString("EnterChannelName", R.string.EnterChannelName)); if (nameToSet != null) { nameTextView.setText(nameToSet); nameToSet = null; } nameTextView.setMaxLines(4); nameTextView .setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); //nameTextView.setHintTextColor(0xff979797); nameTextView.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); nameTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); InputFilter[] inputFilters = new InputFilter[1]; inputFilters[0] = new InputFilter.LengthFilter(100); nameTextView.setFilters(inputFilters); nameTextView.setPadding(0, 0, 0, AndroidUtilities.dp(8)); AndroidUtilities.clearCursorDrawable(nameTextView); nameTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text)); frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 16 : 96, 0, LocaleController.isRTL ? 96 : 16, 0)); nameTextView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { avatarDrawable.setInfo(5, nameTextView.length() > 0 ? nameTextView.getText().toString() : null, null, false); avatarImage.invalidate(); } }); descriptionTextView = new EditText(context); descriptionTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); //descriptionTextView.setHintTextColor(0xff979797); descriptionTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text)); descriptionTextView.setPadding(0, 0, 0, AndroidUtilities.dp(6)); descriptionTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); descriptionTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); descriptionTextView.setImeOptions(EditorInfo.IME_ACTION_DONE); inputFilters = new InputFilter[1]; inputFilters[0] = new InputFilter.LengthFilter(120); descriptionTextView.setFilters(inputFilters); descriptionTextView .setHint(LocaleController.getString("DescriptionPlaceholder", R.string.DescriptionPlaceholder)); AndroidUtilities.clearCursorDrawable(descriptionTextView); linearLayout.addView(descriptionTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 24, 18, 24, 0)); descriptionTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { if (i == EditorInfo.IME_ACTION_DONE && doneButton != null) { doneButton.performClick(); return true; } return false; } }); descriptionTextView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { } }); TextView helpTextView = new TextView(context); helpTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); //helpTextView.setTextColor(0xff6d6d72); helpTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); helpTextView.setText(LocaleController.getString("DescriptionInfo", R.string.DescriptionInfo)); linearLayout.addView(helpTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 24, 10, 24, 20)); } else if (currentStep == 1) { actionBar.setTitle(LocaleController.getString("ChannelSettings", R.string.ChannelSettings)); fragmentView.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background)); LinearLayout linearLayout2 = new LinearLayout(context); linearLayout2.setOrientation(LinearLayout.VERTICAL); linearLayout2.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background)); linearLayout2.setElevation(AndroidUtilities.dp(2)); linearLayout.addView(linearLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); radioButtonCell1 = new RadioButtonCell(context); radioButtonCell1.setElevation(0); radioButtonCell1.setForeground(R.drawable.list_selector); radioButtonCell1.setTextAndValue(LocaleController.getString("ChannelPublic", R.string.ChannelPublic), LocaleController.getString("ChannelPublicInfo", R.string.ChannelPublicInfo), !isPrivate, false); linearLayout2.addView(radioButtonCell1, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); radioButtonCell1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isPrivate) { return; } isPrivate = false; updatePrivatePublic(); } }); radioButtonCell2 = new RadioButtonCell(context); radioButtonCell2.setElevation(0); radioButtonCell2.setForeground(R.drawable.list_selector); radioButtonCell2.setTextAndValue(LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate), LocaleController.getString("ChannelPrivateInfo", R.string.ChannelPrivateInfo), isPrivate, false); linearLayout2.addView(radioButtonCell2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); radioButtonCell2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isPrivate) { return; } isPrivate = true; updatePrivatePublic(); } }); sectionCell = new ShadowSectionCell(context); linearLayout.addView(sectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); linkContainer = new LinearLayout(context); linkContainer.setOrientation(LinearLayout.VERTICAL); linkContainer.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background)); linkContainer.setElevation(AndroidUtilities.dp(2)); linearLayout.addView(linkContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); headerCell = new HeaderCell(context); linkContainer.addView(headerCell); publicContainer = new LinearLayout(context); publicContainer.setOrientation(LinearLayout.HORIZONTAL); linkContainer.addView(publicContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 17, 7, 17, 0)); EditText editText = new EditText(context); editText.setText("telegram.me/"); editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); //editText.setHintTextColor(0xff979797); editText.setTextColor(ContextCompat.getColor(context, R.color.primary_text)); editText.setMaxLines(1); editText.setLines(1); editText.setEnabled(false); editText.setBackgroundDrawable(null); editText.setPadding(0, 0, 0, 0); editText.setSingleLine(true); editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); editText.setImeOptions(EditorInfo.IME_ACTION_DONE); publicContainer.addView(editText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 36)); nameTextView = new EditText(context); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); //nameTextView.setHintTextColor(0xff979797); nameTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text)); nameTextView.setMaxLines(1); nameTextView.setLines(1); nameTextView.setBackgroundDrawable(null); nameTextView.setPadding(0, 0, 0, 0); nameTextView.setSingleLine(true); nameTextView.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); nameTextView.setImeOptions(EditorInfo.IME_ACTION_DONE); nameTextView.setHint( LocaleController.getString("ChannelUsernamePlaceholder", R.string.ChannelUsernamePlaceholder)); AndroidUtilities.clearCursorDrawable(nameTextView); publicContainer.addView(nameTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36)); nameTextView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { checkUserName(nameTextView.getText().toString()); } @Override public void afterTextChanged(Editable editable) { } }); privateContainer = new TextBlockCell(context); privateContainer.setForeground(R.drawable.list_selector); privateContainer.setElevation(0); linkContainer.addView(privateContainer); privateContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (invite == null) { return; } try { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext .getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("label", invite.link); clipboard.setPrimaryClip(clip); Toast.makeText(getParentActivity(), LocaleController.getString("LinkCopied", R.string.LinkCopied), Toast.LENGTH_SHORT) .show(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); checkTextView = new TextView(context); checkTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); checkTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); checkTextView.setVisibility(View.GONE); linkContainer.addView(checkTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 17, 3, 17, 7)); typeInfoCell = new TextInfoPrivacyCell(context); //typeInfoCell.setBackgroundResource(R.drawable.greydivider_bottom); linearLayout.addView(typeInfoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); loadingAdminedCell = new LoadingCell(context); linearLayout.addView(loadingAdminedCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); adminedInfoCell = new TextInfoPrivacyCell(context); //adminedInfoCell.setBackgroundResource(R.drawable.greydivider_bottom); linearLayout.addView(adminedInfoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); updatePrivatePublic(); } else if (currentStep == 2) { actionBar.setTitle(LocaleController.getString("ChannelAddMembers", R.string.ChannelAddMembers)); actionBar.setSubtitle(LocaleController.formatPluralString("Members", selectedContacts.size())); searchListViewAdapter = new SearchAdapter(context, null, false, false, false, false); searchListViewAdapter.setCheckedMap(selectedContacts); searchListViewAdapter.setUseUserCell(true); listViewAdapter = new ContactsAdapter(context, 1, false, null, false); listViewAdapter.setCheckedMap(selectedContacts); FrameLayout frameLayout = new FrameLayout(context); frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.chat_list_background)); linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); nameTextView = new EditText(context); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); //nameTextView.setHintTextColor(0xff979797); nameTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text)); nameTextView.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_MULTI_LINE); nameTextView.setMinimumHeight(AndroidUtilities.dp(54)); nameTextView.setSingleLine(false); nameTextView.setLines(2); nameTextView.setMaxLines(2); nameTextView.setVerticalScrollBarEnabled(true); nameTextView.setHorizontalScrollBarEnabled(false); nameTextView.setPadding(0, 0, 0, 0); nameTextView.setHint(LocaleController.getString("AddMutual", R.string.AddMutual)); nameTextView.setTextIsSelectable(false); nameTextView.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI); nameTextView .setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); AndroidUtilities.clearCursorDrawable(nameTextView); frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 10, 0, 10, 0)); nameTextView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { if (!ignoreChange) { beforeChangeIndex = nameTextView.getSelectionStart(); changeString = new SpannableString(charSequence); } } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { if (!ignoreChange) { boolean search = false; int afterChangeIndex = nameTextView.getSelectionEnd(); if (editable.toString().length() < changeString.toString().length()) { String deletedString = ""; try { deletedString = changeString.toString().substring(afterChangeIndex, beforeChangeIndex); } catch (Exception e) { FileLog.e("tmessages", e); } if (deletedString.length() > 0) { if (searching && searchWas) { search = true; } Spannable span = nameTextView.getText(); for (int a = 0; a < allSpans.size(); a++) { ChipSpan sp = allSpans.get(a); if (span.getSpanStart(sp) == -1) { allSpans.remove(sp); selectedContacts.remove(sp.uid); } } actionBar.setSubtitle( LocaleController.formatPluralString("Members", selectedContacts.size())); listView.invalidateViews(); } else { search = true; } } else { search = true; } if (search) { String text = nameTextView.getText().toString().replace("<", ""); if (text.length() != 0) { searching = true; searchWas = true; if (listView != null) { listView.setAdapter(searchListViewAdapter); searchListViewAdapter.notifyDataSetChanged(); listView.setFastScrollAlwaysVisible(false); listView.setFastScrollEnabled(false); listView.setVerticalScrollBarEnabled(true); } if (emptyTextView != null) { emptyTextView .setText(LocaleController.getString("NoResult", R.string.NoResult)); } searchListViewAdapter.searchDialogs(text); } else { searchListViewAdapter.searchDialogs(null); searching = false; searchWas = false; listView.setAdapter(listViewAdapter); listViewAdapter.notifyDataSetChanged(); listView.setFastScrollAlwaysVisible(true); listView.setFastScrollEnabled(true); listView.setVerticalScrollBarEnabled(false); emptyTextView .setText(LocaleController.getString("NoContacts", R.string.NoContacts)); } } } } }); LinearLayout emptyTextLayout = new LinearLayout(context); emptyTextLayout.setVisibility(View.INVISIBLE); emptyTextLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.addView(emptyTextLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); emptyTextLayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); emptyTextView = new TextView(context); emptyTextView.setTextColor(0xff808080); emptyTextView.setTextSize(20); emptyTextView.setGravity(Gravity.CENTER); emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); emptyTextLayout.addView(emptyTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0.5f)); FrameLayout frameLayout2 = new FrameLayout(context); emptyTextLayout.addView(frameLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0.5f)); listView = new LetterSectionsListView(context); listView.setEmptyView(emptyTextLayout); listView.setVerticalScrollBarEnabled(false); listView.setDivider(null); listView.setDividerHeight(0); listView.setFastScrollEnabled(true); listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); listView.setAdapter(listViewAdapter); listView.setFastScrollAlwaysVisible(true); listView.setVerticalScrollbarPosition( LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); linearLayout.addView(listView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { TLRPC.User user; if (searching && searchWas) { user = (TLRPC.User) searchListViewAdapter.getItem(i); } else { int section = listViewAdapter.getSectionForPosition(i); int row = listViewAdapter.getPositionInSectionForPosition(i); if (row < 0 || section < 0) { return; } user = (TLRPC.User) listViewAdapter.getItem(section, row); } if (user == null) { return; } boolean check = true; if (selectedContacts.containsKey(user.id)) { check = false; try { ChipSpan span = selectedContacts.get(user.id); selectedContacts.remove(user.id); SpannableStringBuilder text = new SpannableStringBuilder(nameTextView.getText()); text.delete(text.getSpanStart(span), text.getSpanEnd(span)); allSpans.remove(span); ignoreChange = true; nameTextView.setText(text); nameTextView.setSelection(text.length()); ignoreChange = false; } catch (Exception e) { FileLog.e("tmessages", e); } } else { ignoreChange = true; ChipSpan span = createAndPutChipForUser(user); if (span != null) { span.uid = user.id; } ignoreChange = false; if (span == null) { return; } } actionBar.setSubtitle(LocaleController.formatPluralString("Members", selectedContacts.size())); if (searching || searchWas) { ignoreChange = true; SpannableStringBuilder ssb = new SpannableStringBuilder(""); 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()); ignoreChange = false; searchListViewAdapter.searchDialogs(null); searching = false; searchWas = false; listView.setAdapter(listViewAdapter); listViewAdapter.notifyDataSetChanged(); listView.setFastScrollAlwaysVisible(true); listView.setFastScrollEnabled(true); listView.setVerticalScrollBarEnabled(false); emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); } else { if (view instanceof UserCell) { ((UserCell) view).setChecked(check, true); } } } }); listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int i) { if (i == SCROLL_STATE_TOUCH_SCROLL) { AndroidUtilities.hideKeyboard(nameTextView); } if (listViewAdapter != null) { listViewAdapter.setIsScrolling(i != SCROLL_STATE_IDLE); } } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (absListView.isFastScrollEnabled()) { AndroidUtilities.clearDrawableAnimation(absListView); } } }); } return fragmentView; }