Java Code Examples for android.widget.TextView#getText()

The following examples show how to use android.widget.TextView#getText() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: android-test   File: ViewMatchers.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean matchesSafely(TextView textView) {
  if (null == expectedText) {
    try {
      expectedText = textView.getResources().getString(resourceId);
      resourceName = textView.getResources().getResourceEntryName(resourceId);
    } catch (Resources.NotFoundException ignored) {
      /* view could be from a context unaware of the resource id. */
    }
  }
  CharSequence actualText;
  switch (method) {
    case GET_TEXT:
      actualText = textView.getText();
      break;
    case GET_HINT:
      actualText = textView.getHint();
      break;
    default:
      throw new IllegalStateException("Unexpected TextView method: " + method.toString());
  }
  // FYI: actualText may not be string ... its just a char sequence convert to string.
  return null != expectedText
      && null != actualText
      && expectedText.equals(actualText.toString());
}
 
Example 2
/**
 * Highlights all the {@link Mentionable}s in the test {@link Comment}.
 */
private void highlightMentions(final TextView commentTextView, final List<Mentionable> mentions) {
    if(commentTextView != null && mentions != null && !mentions.isEmpty()) {
        final Spannable spannable = new SpannableString(commentTextView.getText());

        for (Mentionable mention: mentions) {
            if (mention != null) {
                final int start = mention.getMentionOffset();
                final int end = start + mention.getMentionLength();

                if (commentTextView.length() >= end) {
                    spannable.setSpan(new ForegroundColorSpan(orange), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    commentTextView.setText(spannable, TextView.BufferType.SPANNABLE);
                } else {
                    //Something went wrong.  The expected text that we're trying to highlight does not
                    // match the actual text at that position.
                    Log.w("Mentions Sample", "Mention lost. [" + mention + "]");
                }
            }
        }
    }
}
 
Example 3
Source Project: sctalk   File: IMUIHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static void setTextHilighted(TextView textView, String text,SearchElement searchElement) {
    textView.setText(text);
    if (textView == null
            || TextUtils.isEmpty(text)
            || searchElement ==null) {
        return;
    }

    int startIndex = searchElement.startIndex;
    int endIndex = searchElement.endIndex;
    if (startIndex < 0 || endIndex > text.length()) {
        return;
    }
    // 开始高亮处理
    int color =  Color.rgb(69, 192, 26);
    textView.setText(text, BufferType.SPANNABLE);
    Spannable span = (Spannable) textView.getText();
    span.setSpan(new ForegroundColorSpan(color), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
 
Example 4
Source Project: Markwon   File: GifProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private static Spannable spannable(@NonNull TextView textView) {
    final CharSequence charSequence = textView.getText();
    if (charSequence instanceof Spannable) {
        return (Spannable) charSequence;
    }
    return null;
}
 
Example 5
Source Project: zone-sdk   File: TextViewLinkActivity.java    License: MIT License 5 votes vote down vote up
private void changeColor() {
    TextView textView = (TextView) findViewById(R.id.changeColor);
    textView.getText();
    SpannableStringBuilder ssb = new SpannableStringBuilder(textView.getText());
    ssb.setSpan(new ForegroundColorSpanAni(textView), 0, textView.getText().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(ssb);
}
 
Example 6
Source Project: BaseProject   File: BaseDialog.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 提取出 给定的一个View的 Text
 * @param mightAsWellTextView 最好是TextView类型的View ^.^
 * @return View上的文本
 */
public CharSequence extractTextOfView(View mightAsWellTextView) {
    if (mightAsWellTextView instanceof TextView) {
        TextView textView = (TextView) mightAsWellTextView;
        return textView.getText();
    }
    return null;
}
 
Example 7
public static void addLinks(TextView view) {
    CharSequence content = view.getText();
    view.setText(convertNormalStringToSpannableString(content.toString()));
    if (view.getLinksClickable()) {
        view.setMovementMethod(LongClickableLinkMovementMethod.getInstance());
    }
}
 
Example 8
/**
 * 在一个TextView上追加一行日志.
 * @param logTextView
 * @param log
 */
public static void println(TextView logTextView, CharSequence log) {
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
    String timestamp = sdf.format(new Date());

    CharSequence newText = timestamp + ": " + log;
    CharSequence oldText = logTextView.getText();
    if (oldText == null || oldText.length() <= 0) {
        logTextView.setText(newText);
    }
    else {
        logTextView.setText(oldText + "\n" + newText);
    }
}
 
Example 9
/**
 * Format appropriately the suggested word in {@link #mWordViews} specified by
 * <code>positionInStrip</code>. When the suggested word doesn't exist, the corresponding
 * {@link TextView} will be disabled and never respond to user interaction. The suggested word
 * may be shrunk or ellipsized to fit in the specified width.
 *
 * The <code>positionInStrip</code> argument is the index in the suggestion strip. The indices
 * increase towards the right for LTR scripts and the left for RTL scripts, starting with 0.
 * The position of the most important suggestion is in {@link #mCenterPositionInStrip}. This
 * usually doesn't match the index in <code>suggedtedWords</code> -- see
 * {@link #getPositionInSuggestionStrip(int,SuggestedWords)}.
 *
 * @param positionInStrip the position in the suggestion strip.
 * @param width the maximum width for layout in pixels.
 * @return the {@link TextView} containing the suggested word appropriately formatted.
 */
private TextView layoutWord(final Context context, final int positionInStrip, final int width) {
    final TextView wordView = mWordViews.get(positionInStrip);
    final CharSequence word = wordView.getText();
    if (positionInStrip == mCenterPositionInStrip && mMoreSuggestionsAvailable) {
        // TODO: This "more suggestions hint" should have a nicely designed icon.
        wordView.setCompoundDrawablesWithIntrinsicBounds(
                null, null, null, mMoreSuggestionsHint);
        // HACK: Align with other TextViews that have no compound drawables.
        wordView.setCompoundDrawablePadding(-mMoreSuggestionsHint.getIntrinsicHeight());
    } else {
        wordView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
    }
    // {@link StyleSpan} in a content description may cause an issue of TTS/TalkBack.
    // Use a simple {@link String} to avoid the issue.
    wordView.setContentDescription(
            TextUtils.isEmpty(word)
                ? context.getResources().getString(R.string.spoken_empty_suggestion)
                : word.toString());
    final CharSequence text = getEllipsizedTextWithSettingScaleX(
            word, width, wordView.getPaint());
    final float scaleX = wordView.getTextScaleX();
    wordView.setText(text); // TextView.setText() resets text scale x to 1.0.
    wordView.setTextScaleX(scaleX);
    // A <code>wordView</code> should be disabled when <code>word</code> is empty in order to
    // make it unclickable.
    // With accessibility touch exploration on, <code>wordView</code> should be enabled even
    // when it is empty to avoid announcing as "disabled".
    wordView.setEnabled(!TextUtils.isEmpty(word)
            || AccessibilityUtils.getInstance().isTouchExplorationEnabled());
    return wordView;
}
 
Example 10
Source Project: glimmr   File: TextUtils.java    License: Apache License 2.0 5 votes vote down vote up
public void colorTextViewSpan(TextView view, String fulltext,
        String subtext, int color) {
    view.setText(fulltext, TextView.BufferType.SPANNABLE);
    Spannable str = (Spannable) view.getText();
    int i = fulltext.indexOf(subtext);
    try {
        str.setSpan(new ForegroundColorSpan(color), i, i+subtext.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    } catch (Exception e) {
        e.printStackTrace();
        Log.d(TAG, "fulltext: " + fulltext);
        Log.d(TAG, "subtext: " + subtext);
    }
}
 
Example 11
private static void startSelection(TextView textView, int start, int end) {
    final CharSequence text = textView.getText();
    if (SUPPORTED && start >= 0 && end > start && textView.isTextSelectable() && text instanceof Spannable) {
        final Spannable spannable = (Spannable) text;
        start = Math.min(start, spannable.length());
        end = Math.min(end, spannable.length());
        Selection.setSelection(spannable, start, end);
        try {
            final Object editor = FIELD_EDITOR != null ? FIELD_EDITOR.get(textView) : textView;
            METHOD_START_SELECTION.invoke(editor);
        } catch (Exception e) {
        }
    }
}
 
Example 12
@Override
public void onClick(View widget) {

    if(widget instanceof TextView){
        TextView tv = (TextView) widget;
        if(tv.getText() instanceof Spanned){
            Spanned s = (Spanned) tv.getText();
            int start = s.getSpanStart(this);
            int end = s.getSpanEnd(this);
            clickableListener.onClickableEvent(s.subSequence(start, end));
        }
    }
}
 
Example 13
Source Project: BookLoadingView   File: JumpingBeans.java    License: Apache License 2.0 5 votes vote down vote up
private static void cleanupSpansFrom(TextView tv) {
    if (tv != null) {
        CharSequence text = tv.getText();
        if (text instanceof Spanned) {
            CharSequence cleanText = removeJumpingBeansSpansFrom((Spanned) text);
            tv.setText(cleanText);
        }
    }
}
 
Example 14
Source Project: FireFiles   File: AboutActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void initControls() {

		int accentColor = ColorUtils.getTextColorForBackground(SettingsActivity.getPrimaryColor(),
				MIN_CONTRAST_TITLE_TEXT);
		TextView logo = (TextView)findViewById(R.id.logo);
		logo.setTextColor(accentColor);
		String header = logo.getText() + getSuffix() + " v" + BuildConfig.VERSION_NAME;
		logo.setText(header);

		TextView action_rate = (TextView)findViewById(R.id.action_rate);
		TextView action_support = (TextView)findViewById(R.id.action_support);
		TextView action_share = (TextView)findViewById(R.id.action_share);
		TextView action_feedback = (TextView)findViewById(R.id.action_feedback);

		action_rate.setOnClickListener(this);
		action_support.setOnClickListener(this);
		action_share.setOnClickListener(this);
		action_feedback.setOnClickListener(this);

		if(Utils.isOtherBuild()){
			action_rate.setVisibility(View.GONE);
			action_support.setVisibility(View.GONE);
		} else if(DocumentsApplication.isTelevision()){
			action_share.setVisibility(View.GONE);
			action_feedback.setVisibility(View.GONE);
		}
	}
 
Example 15
Source Project: datmusic-android   File: U.java    License: Apache License 2.0 5 votes vote down vote up
public static void stripUnderlines(TextView textView) {
    Spannable s = (Spannable) textView.getText();
    URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
    for(URLSpan span : spans) {
        int start = s.getSpanStart(span);
        int end = s.getSpanEnd(span);
        s.removeSpan(span);
        span = new URLSpanNoUnderline(span.getURL());
        s.setSpan(span, start, end, 0);
    }
    textView.setText(s);
}
 
Example 16
Source Project: AndroidChromium   File: InfoBar.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CharSequence getAccessibilityText() {
    if (mView == null) return "";
    TextView messageView = (TextView) mView.findViewById(R.id.infobar_message);
    if (messageView == null) return "";
    return messageView.getText() + mContext.getString(R.string.bottom_bar_screen_position);
}
 
Example 17
Source Project: RichText   File: ImageTarget.java    License: MIT License 5 votes vote down vote up
void resetText() {
    TextView tv = textViewWeakReference.get();
    if (tv != null) {
        CharSequence cs = tv.getText();
        tv.setText(cs);
    }
}
 
Example 18
Source Project: commcare-android   File: QuestionWidget.java    License: Apache License 2.0 5 votes vote down vote up
private void stripUnderlines(TextView textView) {
    Spannable s = (Spannable)textView.getText();
    URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
    for (URLSpan span : spans) {
        int start = s.getSpanStart(span);
        int end = s.getSpanEnd(span);
        s.removeSpan(span);
        span = new URLSpanNoUnderline(span.getURL());
        s.setSpan(span, start, end, 0);
    }
    textView.setText(s);
}
 
Example 19
@Override
public void onResponse(ImageContainer response, boolean isImmediate) {
    if (mTextView.getTag(R.id.poste_image_getter) == UrlImageGetter.this && response.getBitmap() != null) {
        BitmapDrawable drawable = new BitmapDrawable(mRes, response.getBitmap());
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        String src = response.getRequestUrl();
        // redraw the image by invalidating the container
        // 由于下面重新设置了ImageSpan,所以这里invalidate就不必要了吧
        // urlDrawable.invalidateSelf();
        // UrlImageGetter.this.mTextView.invalidate();

        // TODO 这种方式基本完美解决显示图片问题, blog?
        // 把提取到下面显示的图片在放出来? 然后点击任何图片 进入到 帖子图片浏览界面。。?
        TextView v = UrlImageGetter.this.mTextView;
        CharSequence text = v.getText();
        if (!(text instanceof Spannable)) {
            return;
        }
        Spannable spanText = (Spannable) text;
        @SuppressWarnings("unchecked") ArrayList<String> imgs = (ArrayList<String>) v.getTag(R.id.poste_image_data);
        ImageSpan[] imageSpans = spanText.getSpans(0, spanText.length(), ImageSpan.class);
        L.i("%b X Recycled %b src: %s", isImmediate, response.getBitmap().isRecycled(), src);
        for (ImageSpan imgSpan : imageSpans) {
            int start = spanText.getSpanStart(imgSpan);
            int end = spanText.getSpanEnd(imgSpan);
            L.i("%d-%d :%s", start, end, imgSpan.getSource());
            String url = imgSpan.getSource();
            url = checkUrl(url);
            if (src.equals(url)) {
                spanText.removeSpan(imgSpan);
                ImageSpan is = new ImageSpan(drawable, src, ImageSpan.ALIGN_BASELINE);
                spanText.setSpan(is, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            if (imgs != null && imgs.contains(src)) {
                ImageClickableSpan ics = new ImageClickableSpan(src);
                spanText.setSpan(ics, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

        }
        v.setText(spanText);
    }

}
 
Example 20
Builder(int id, @Nullable ViewHierarchyElementAndroid parent, View fromView) {
  // Bookkeeping
  this.id = id;
  this.parentId = (parent != null) ? parent.getId() : null;

  this.drawingOrder = null;

  // API 16+ properties
  this.scrollable = AT_16 ? fromView.isScrollContainer() : null;

  // API 11+ properties
  this.backgroundDrawableColor =
      (AT_11 && (fromView != null) && (fromView.getBackground() instanceof ColorDrawable))
          ? ((ColorDrawable) fromView.getBackground()).getColor()
          : null;

  // Base properties
  this.visibleToUser = ViewAccessibilityUtils.isVisibleToUser(fromView);
  this.className = fromView.getClass().getName();
  this.accessibilityClassName = null;
  this.packageName = fromView.getContext().getPackageName();
  this.resourceName =
      (fromView.getId() != View.NO_ID)
          ? ViewAccessibilityUtils.getResourceNameForView(fromView)
          : null;
  this.contentDescription = SpannableStringAndroid.valueOf(fromView.getContentDescription());
  this.enabled = fromView.isEnabled();
  if (fromView instanceof TextView) {
    TextView textView = (TextView) fromView;
    // Hint text takes precedence if no text is present.
    CharSequence text = textView.getText();
    if (TextUtils.isEmpty(text)) {
      text = textView.getHint();
    }
    this.text = SpannableStringAndroid.valueOf(text);
    this.textSize = textView.getTextSize();

    this.textColor = textView.getCurrentTextColor();
    this.typefaceStyle =
        (textView.getTypeface() != null) ? textView.getTypeface().getStyle() : null;
  } else {
    this.text = null;
    this.textSize = null;
    this.textColor = null;
    this.typefaceStyle = null;
  }

  this.importantForAccessibility = ViewAccessibilityUtils.isImportantForAccessibility(fromView);
  this.clickable = fromView.isClickable();
  this.longClickable = fromView.isLongClickable();
  this.focusable = fromView.isFocusable();
  this.editable = ViewAccessibilityUtils.isViewEditable(fromView);
  this.canScrollForward =
      (ViewCompat.canScrollVertically(fromView, 1)
          || ViewCompat.canScrollHorizontally(fromView, 1));
  this.canScrollBackward =
      (ViewCompat.canScrollVertically(fromView, -1)
          || ViewCompat.canScrollHorizontally(fromView, -1));
  this.checkable = (fromView instanceof Checkable);
  this.checked = (fromView instanceof Checkable) ? ((Checkable) fromView).isChecked() : null;
  this.hasTouchDelegate = (fromView.getTouchDelegate() != null);
  this.touchDelegateBounds = ImmutableList.of(); // Unavailable from the View API
  this.boundsInScreen = getBoundsInScreen(fromView);
  this.nonclippedHeight = fromView.getHeight();
  this.nonclippedWidth = fromView.getWidth();
  this.actionList = ImmutableList.of(); // Unavailable from the View API
}