List of usage examples for android.text Spanned toString
public String toString();
From source file:org.openlmis.core.view.widget.InputFilterMinMax.java
@Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { try {// w w w . j av a2 s. c o m int input = Integer.parseInt(dest.toString() + source.toString()); if (input <= max && input >= min) { return null; } } catch (NumberFormatException nfe) { return StringUtils.EMPTY; } return StringUtils.EMPTY; }
From source file:org.totschnig.myexpenses.util.Utils.java
public static void configDecimalSeparator(final EditText editText, final char decimalSeparator, final int fractionDigits) { // mAmountText.setInputType( // InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL); // due to bug in Android platform // http://code.google.com/p/android/issues/detail?id=2626 // the soft keyboard if it occupies full screen in horizontal orientation // does not display the , as comma separator // TODO we should take into account the arab separator as well final char otherSeparator = decimalSeparator == '.' ? ',' : '.'; editText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); editText.setFilters(new InputFilter[] { new InputFilter() { @Override//from w w w . j a v a2 s . c o m public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { int separatorPositionInDest = dest.toString().indexOf(decimalSeparator); char[] v = new char[end - start]; TextUtils.getChars(source, start, end, v, 0); String input = new String(v).replace(otherSeparator, decimalSeparator); if (fractionDigits == 0 || separatorPositionInDest != -1 || dest.length() - dend > fractionDigits) { input = input.replace(String.valueOf(decimalSeparator), ""); } else { int separatorPositionInSource = input.lastIndexOf(decimalSeparator); if (separatorPositionInSource != -1) { //we make sure there is only one separator in the input and after the separator we do not use //more minor digits as allowed int existingMinorUnits = dest.length() - dend; int additionalAllowedMinorUnits = fractionDigits - existingMinorUnits; int additionalPossibleMinorUnits = input.length() - separatorPositionInSource - 1; int extractMinorUnits = additionalPossibleMinorUnits >= additionalAllowedMinorUnits ? additionalAllowedMinorUnits : additionalPossibleMinorUnits; input = input.substring(0, separatorPositionInSource) .replace(String.valueOf(decimalSeparator), "") + decimalSeparator + (extractMinorUnits > 0 ? input.substring(separatorPositionInSource + 1, separatorPositionInSource + 1 + extractMinorUnits) : ""); } } if (fractionDigits == 0) { return input; } if (separatorPositionInDest != -1 && dend > separatorPositionInDest && dstart > separatorPositionInDest) { int existingMinorUnits = dest.length() - (separatorPositionInDest + 1); int remainingMinorUnits = fractionDigits - existingMinorUnits; if (remainingMinorUnits < 1) { return ""; } return input.length() > remainingMinorUnits ? input.substring(0, remainingMinorUnits) : input; } else { return input; } } }, new InputFilter.LengthFilter(16) }); }
From source file:com.jins_meme.bridge.OSCConfigFragment.java
@Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); handler = new Handler(); layout = (LinearLayout) view.findViewById(R.id.osc_layout); layout.setOnTouchListener(new OnTouchListener() { @Override// w w w . j a v a 2 s . c o m public boolean onTouch(View view, MotionEvent motionEvent) { Log.d("DEBUG", "view touch."); layout.requestFocus(); return false; } }); InputFilter[] filters = new InputFilter[1]; filters[0] = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (end > start) { String destTxt = dest.toString(); String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend); if (!resultingTxt .matches("^\\d{1,3}(\\." + "(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) { return ""; } else { String[] splits = resultingTxt.split("\\."); for (String split : splits) { if (Integer.valueOf(split) > 255) { return ""; } } } } return null; } }; etRemoteIP = (EditText) view.findViewById(R.id.remote_ip); String savedRemoteIP = ((MainActivity) getActivity()).getSavedValue("REMOTE_IP", "255.255.255.255"); if (savedRemoteIP.equals("255.255.255.255")) { etRemoteIP.setText(MemeOSC.getRemoteIPv4Address()); } else { etRemoteIP.setText(savedRemoteIP); } etRemoteIP.setFilters(filters); etRemoteIP.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if (!b) { InputMethodManager imm = (InputMethodManager) getActivity() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } }); etRemoteIP.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { Log.d("DEBUG", "after text changed " + editable.toString()); ((MainActivity) getActivity()).autoSaveValue("REMOTE_IP", editable.toString()); testOSC.setRemoteIP(etRemoteIP.getText().toString()); testOSC.initSocket(); } }); etRemotePort = (EditText) view.findViewById(R.id.remote_port); etRemotePort.setText(String.valueOf(((MainActivity) getActivity()).getSavedValue("REMOTE_PORT", 10316))); etRemotePort.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if (!b) { InputMethodManager imm = (InputMethodManager) getActivity() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } }); etRemotePort.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { Log.d("DEBUG", "after text changed " + editable.toString()); if (editable.toString().length() > 0) { ((MainActivity) getActivity()).autoSaveValue("REMOTE_PORT", Integer.valueOf(editable.toString())); testOSC.setRemotePort(Integer.parseInt(editable.toString())); testOSC.initSocket(); } } }); etHostIP = (EditText) view.findViewById(R.id.host_ip); etHostIP.setText(MemeOSC.getHostIPv4Address()); etHostIP.setEnabled(false); etHostPort = (EditText) view.findViewById(R.id.host_port); etHostPort.setText(String.valueOf(((MainActivity) getActivity()).getSavedValue("HOST_PORT", 11316))); etHostPort.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if (!b) { InputMethodManager imm = (InputMethodManager) getActivity() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } }); etHostPort.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { Log.d("DEBUG", "after text changed " + editable.toString()); if (editable.toString().length() > 0) { ((MainActivity) getActivity()).autoSaveValue("HOST_PORT", Integer.valueOf(editable.toString())); testOSC.setHostPort(Integer.parseInt(editable.toString())); testOSC.initSocket(); } } }); btnTest = (Button) view.findViewById(R.id.remote_test); btnTest.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { layout.requestFocus(); testOSC.setAddress("/meme/bridge", "/test"); testOSC.setTypeTag("si"); testOSC.addArgument(etRemoteIP.getText().toString()); testOSC.addArgument(Integer.parseInt(etRemotePort.getText().toString())); testOSC.flushMessage(); } }); testOSC = new MemeOSC(); testOSC.setRemoteIP(etRemoteIP.getText().toString()); testOSC.setRemotePort(Integer.parseInt(etRemotePort.getText().toString())); testOSC.setHostPort(Integer.parseInt(etHostPort.getText().toString())); testOSC.initSocket(); isShown = true; Thread rcvTestThread = new Thread(new ReceiveTestTRunnable()); rcvTestThread.start(); }
From source file:tk.wasdennnoch.androidn_ify.utils.NotificationColorUtil.java
/** * Inverts all the grayscale colors set by {@link TextAppearanceSpan}s on * the text.//from w w w . ja v a 2s . co m * * @param charSequence The text to process. * @return The color inverted text. */ public CharSequence invertCharSequenceColors(CharSequence charSequence) { if (charSequence instanceof Spanned) { Spanned ss = (Spanned) charSequence; Object[] spans = ss.getSpans(0, ss.length(), Object.class); SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString()); for (Object span : spans) { Object resultSpan = span; if (span instanceof TextAppearanceSpan) { resultSpan = processTextAppearanceSpan((TextAppearanceSpan) span); } builder.setSpan(resultSpan, ss.getSpanStart(span), ss.getSpanEnd(span), ss.getSpanFlags(span)); } return builder; } return charSequence; }
From source file:com.googlecode.eyesfree.brailleback.SearchNavigationMode.java
/** * Formats some braille content from an {@link AccessibilityNodeInfoCompat}. * Marks the description with a cursor right after the last character * matching the search query. Returns content with keep pan strategy * by default, or reset pan strategy if there is no matched node stored yet. *//* w ww .java 2 s . c om*/ private DisplayManager.Content formatNodeToBraille(AccessibilityNodeInfoCompat node) { if (node == null) { return null; } DisplayManager.Content content = mNodeBrailler.brailleNode(node); if (content == null) { return null; } Spanned spanned = content.getSpanned(); if (spanned == null) { LogUtils.log(this, Log.ERROR, "No text for node"); return null; } // Find index of match and the index corresponding to the // end of the matched text so we know where to place the cursor. String lowerCase = spanned.toString().toLowerCase(); String matchText = mQueryText.toString().toLowerCase(); AccessibilityNodeInfoCompat spanNode = (AccessibilityNodeInfoCompat) DisplaySpans.getEqualSpan(spanned, node); int cursorIndex = -1; if (spanNode != null) { int nodeIndex = spanned.getSpanStart(spanNode); if (nodeIndex >= 0 && nodeIndex < lowerCase.length()) { int matchIndex = lowerCase.indexOf(matchText, nodeIndex); if (matchIndex >= 0 && matchIndex <= lowerCase.length()) { cursorIndex = matchIndex + matchText.length(); } } } // Add prefix to what's displayed to mark this as a search result. String prefix = mAccessibilityService.getString(R.string.search_result_prefix); int lengthDiff = prefix.length(); SpannableStringBuilder sb = (SpannableStringBuilder) spanned; sb.insert(0, prefix); // If match in this node, add cursor at end of match. if (cursorIndex != -1) { DisplaySpans.addSelection(sb, cursorIndex + lengthDiff, cursorIndex + lengthDiff); } // No matched node stored, means we have just activated search mode, // so we want to reset the panning frame so we can see the search // prefix. int panStrategy = AccessibilityNodeInfoRef.isNull(mMatchedNode) ? DisplayManager.Content.PAN_RESET : DisplayManager.Content.PAN_KEEP; return content.setPanStrategy(panStrategy); }
From source file:com.opencabinetlabs.destinycommunityhub.ui.MainActivity.java
@Subscribe public void onPodcastEvent(PlaybackEvent event) { if (event.action.equalsIgnoreCase(PodcastService.ACTION_PLAY) || event.action.equalsIgnoreCase(PodcastService.ACTION_PAUSE)) { currentlyPlayingBundle = event.podcast_info; if (currentlyPlayingBundle != null) { int progress = currentlyPlayingBundle.getInt(PodcastService.PODCAST_DURATION); mSeeker.setMax(progress);//from w ww. ja v a2s.com mTotalDuration.setText(String.format("%d:%02d", TimeUnit.MILLISECONDS.toMinutes(progress), TimeUnit.MILLISECONDS.toSeconds(progress) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(progress)))); String title = currentlyPlayingBundle.getString(PodcastService.PODCAST_TITLE); mPodcastTitle.setText(title); mExpPodcastTitle.setText(title); String artist = currentlyPlayingBundle.getString(PodcastService.PODCAST_ARTIST).trim(); mPodcastArtist.setText(artist); mExpPodcastArtist.setText(artist); try { Spanned desc = Html .fromHtml((currentlyPlayingBundle.getString(PodcastService.PODCAST_DESCRIPTION))); if (desc.toString() != null) { mExpPodcastDescription.setText(desc); Linkify.addLinks(mExpPodcastDescription, Linkify.WEB_URLS); } } catch (Exception e) { Timber.e("error converting text" + e.toString()); mExpPodcastDescription.setText(""); } mPodcastArtwork.setImageDrawable( getResources().getDrawable(currentlyPlayingBundle.getInt(PodcastService.PODCAST_ARTWORK))); mExpPodcastArtwork.setImageDrawable( getResources().getDrawable(currentlyPlayingBundle.getInt(PodcastService.PODCAST_ARTWORK))); mPodcastPanel.setVisibility(View.VISIBLE); } if (event.action.equalsIgnoreCase(PodcastService.ACTION_PLAY)) { mPlayPauseButton.setImageResource(R.drawable.ic_action_playback_pause); } else if (event.action.equalsIgnoreCase(PodcastService.ACTION_PAUSE)) { mPlayPauseButton.setImageResource(R.drawable.ic_action_playback_play); } } else if (event.action.equalsIgnoreCase(PodcastService.ACTION_STOP)) { mPodcastPanel.setVisibility(View.GONE); } }
From source file:com.nttec.everychan.ui.presentation.BoardFragment.java
@Override public boolean onContextItemSelected(MenuItem item) { //? ? -//from w ww . j a va 2 s . c o m switch (item.getItemId()) { case R.id.context_menu_thumb_load_thumb: bitmapCache.asyncGet( ChanModels.hashAttachmentModel((AttachmentModel) lastContextMenuAttachment.getTag()), ((AttachmentModel) lastContextMenuAttachment.getTag()).thumbnail, resources.getDimensionPixelSize(R.dimen.post_thumbnail_size), chan, null, imagesDownloadTask, (ImageView) lastContextMenuAttachment.findViewById(R.id.post_thumbnail_image), imagesDownloadExecutor, Async.UI_HANDLER, true, R.drawable.thumbnail_error); return true; case R.id.context_menu_thumb_download: downloadFile((AttachmentModel) lastContextMenuAttachment.getTag()); return true; case R.id.context_menu_thumb_copy_url: String url = chan.fixRelativeUrl(((AttachmentModel) lastContextMenuAttachment.getTag()).path); Clipboard.copyText(activity, url); Toast.makeText(activity, resources.getString(R.string.notification_url_copied, url), Toast.LENGTH_LONG) .show(); return true; case R.id.context_menu_thumb_attachment_info: String info = Attachments.getAttachmentInfoString(chan, ((AttachmentModel) lastContextMenuAttachment.getTag()), resources); Toast.makeText(activity, info, Toast.LENGTH_LONG).show(); return true; case R.id.context_menu_thumb_reverse_search: ReverseImageSearch.openDialog(activity, chan.fixRelativeUrl(((AttachmentModel) lastContextMenuAttachment.getTag()).path)); return true; } //? ? ? int position = lastContextMenuPosition; if (item.getMenuInfo() != null && item.getMenuInfo() instanceof AdapterView.AdapterContextMenuInfo) { position = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position; } if (nullAdapterIsSet || position == -1 || adapter.getCount() <= position) return false; switch (item.getItemId()) { case R.id.context_menu_open_in_new_tab: UrlPageModel modelNewTab = new UrlPageModel(); modelNewTab.chanName = chan.getChanName(); modelNewTab.type = UrlPageModel.TYPE_THREADPAGE; modelNewTab.boardName = tabModel.pageModel.boardName; modelNewTab.threadNumber = adapter.getItem(position).sourceModel.parentThread; String tabTitle = null; String subject = adapter.getItem(position).sourceModel.subject; if (subject != null && subject.length() != 0) { tabTitle = subject; } else { Spanned spannedComment = adapter.getItem(position).spannedComment; if (spannedComment != null) { tabTitle = spannedComment.toString().replace('\n', ' '); if (tabTitle.length() > MAX_TITLE_LENGHT) tabTitle = tabTitle.substring(0, MAX_TITLE_LENGHT); } } if (tabTitle != null) tabTitle = resources.getString(R.string.tabs_title_threadpage_loaded, modelNewTab.boardName, tabTitle); UrlHandler.open(modelNewTab, activity, false, tabTitle); return true; case R.id.context_menu_thread_preview: showThreadPreviewDialog(position); return true; case R.id.context_menu_reply_no_reading: UrlPageModel model = new UrlPageModel(); model.chanName = chan.getChanName(); model.type = UrlPageModel.TYPE_THREADPAGE; model.boardName = tabModel.pageModel.boardName; model.threadNumber = adapter.getItem(position).sourceModel.parentThread; openPostForm(ChanModels.hashUrlPageModel(model), presentationModel.source.boardModel, getSendPostModel(model)); return true; case R.id.context_menu_hide: adapter.getItem(position).hidden = true; database.addHidden(tabModel.pageModel.chanName, tabModel.pageModel.boardName, pageType == TYPE_POSTSLIST ? tabModel.pageModel.threadNumber : adapter.getItem(position).sourceModel.number, pageType == TYPE_POSTSLIST ? adapter.getItem(position).sourceModel.number : null); adapter.notifyDataSetChanged(); return true; case R.id.context_menu_reply: openReply(position, false, null); return true; case R.id.context_menu_reply_with_quote: openReply(position, true, null); return true; case R.id.context_menu_select_text: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && lastContextMenuPosition == -1) { int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); int wantedChild = position - firstPosition; if (wantedChild >= 0 && wantedChild < listView.getChildCount()) { View v = listView.getChildAt(wantedChild); if (v != null && v.getTag() != null && v.getTag() instanceof PostsListAdapter.PostViewTag) { ((PostsListAdapter.PostViewTag) v.getTag()).commentView.startSelection(); return true; } } } Clipboard.copyText(activity, adapter.getItem(position).spannedComment.toString()); Toast.makeText(activity, resources.getString(R.string.notification_comment_copied), Toast.LENGTH_LONG) .show(); return true; case R.id.context_menu_share: UrlPageModel sharePostUrlPageModel = new UrlPageModel(); sharePostUrlPageModel.chanName = chan.getChanName(); sharePostUrlPageModel.type = UrlPageModel.TYPE_THREADPAGE; sharePostUrlPageModel.boardName = tabModel.pageModel.boardName; sharePostUrlPageModel.threadNumber = tabModel.pageModel.threadNumber; sharePostUrlPageModel.postNumber = adapter.getItem(position).sourceModel.number; Intent sharePostIntent = new Intent(Intent.ACTION_SEND); sharePostIntent.setType("text/plain"); sharePostIntent.putExtra(Intent.EXTRA_SUBJECT, chan.buildUrl(sharePostUrlPageModel)); sharePostIntent.putExtra(Intent.EXTRA_TEXT, adapter.getItem(position).spannedComment.toString()); startActivity(Intent.createChooser(sharePostIntent, resources.getString(R.string.share_via))); return true; case R.id.context_menu_delete: DeletePostModel delModel = new DeletePostModel(); delModel.chanName = chan.getChanName(); delModel.boardName = tabModel.pageModel.boardName; delModel.threadNumber = tabModel.pageModel.threadNumber; delModel.postNumber = adapter.getItem(position).sourceModel.number; runDelete(delModel, adapter.getItem(position).sourceModel.attachments != null && adapter.getItem(position).sourceModel.attachments.length > 0); return true; case R.id.context_menu_report: DeletePostModel reportModel = new DeletePostModel(); reportModel.chanName = chan.getChanName(); reportModel.boardName = tabModel.pageModel.boardName; reportModel.threadNumber = tabModel.pageModel.threadNumber; reportModel.postNumber = adapter.getItem(position).sourceModel.number; runReport(reportModel); return true; case R.id.context_menu_subscribe: String chanName = chan.getChanName(); String board = tabModel.pageModel.boardName; String thread = tabModel.pageModel.threadNumber; String post = adapter.getItem(position).sourceModel.number; if (subscriptions.hasSubscription(chanName, board, thread, post)) { subscriptions.removeSubscription(chanName, board, thread, post); for (int i = position; i < adapter.getCount(); ++i) adapter.getItem(i).onUnsubscribe(post); } else { subscriptions.addSubscription(chanName, board, thread, post); for (int i = position; i < adapter.getCount(); ++i) adapter.getItem(i).onSubscribe(post); } adapter.notifyDataSetChanged(); return true; } return false; }
From source file:com.android.mail.compose.ComposeActivity.java
/** * This function might be called from a background thread, so be sure to move everything that * can potentially modify the UI to the main thread (e.g. removeComposingSpans for body). */// www . j a v a 2 s.c o m private Message createMessage(ReplyFromAccount selectedReplyFromAccount, Message refMessage, int mode, Spanned body) { Message message = new Message(); message.id = UIProvider.INVALID_MESSAGE_ID; message.serverId = null; message.uri = null; message.conversationUri = null; message.subject = mSubject.getText().toString(); message.snippet = null; message.setTo(formatSenders(mTo.getText().toString())); message.setCc(formatSenders(mCc.getText().toString())); message.setBcc(formatSenders(mBcc.getText().toString())); message.setReplyTo(null); message.dateReceivedMs = 0; message.bodyHtml = spannedBodyToHtml(body, true); message.bodyText = body.toString(); // Fallback to use the text version if html conversion fails for whatever the reason. final String htmlInPlainText = Utils.convertHtmlToPlainText(message.bodyHtml); if (message.bodyText != null && message.bodyText.trim().length() > 0 && TextUtils.isEmpty(htmlInPlainText)) { LogUtils.w(LOG_TAG, "FAILED HTML CONVERSION: from %d to %d", message.bodyText.length(), htmlInPlainText.length()); Analytics.getInstance().sendEvent(ANALYTICS_CATEGORY_ERRORS, "failed_html_conversion", null, 0); message.bodyHtml = "<p>" + message.bodyText + "</p>"; } message.embedsExternalResources = false; message.refMessageUri = mRefMessage != null ? mRefMessage.uri : null; message.appendRefMessageContent = mQuotedTextView.getQuotedTextIfIncluded() != null; ArrayList<Attachment> attachments = mAttachmentsView.getAttachments(); message.hasAttachments = attachments != null && attachments.size() > 0; message.attachmentListUri = null; message.messageFlags = 0; message.alwaysShowImages = false; message.attachmentsJson = Attachment.toJSONArray(attachments); CharSequence quotedText = mQuotedTextView.getQuotedText(); message.quotedTextOffset = -1; // Just a default value. if (refMessage != null && !TextUtils.isEmpty(quotedText)) { if (!TextUtils.isEmpty(refMessage.bodyHtml)) { // We want the index to point to just the quoted text and not the // "On December 25, 2014..." part of it. message.quotedTextOffset = QuotedTextView.getQuotedTextOffset(quotedText.toString()); } else if (!TextUtils.isEmpty(refMessage.bodyText)) { // We want to point to the entire quoted text. message.quotedTextOffset = QuotedTextView.findQuotedTextIndex(quotedText); } } message.accountUri = null; message.setFrom(computeFromForAccount(selectedReplyFromAccount)); message.draftType = getDraftType(mode); return message; }