Example usage for android.widget TextView getPaint

List of usage examples for android.widget TextView getPaint

Introduction

In this page you can find the example usage for android.widget TextView getPaint.

Prototype

public TextPaint getPaint() 

Source Link

Document

Gets the TextPaint used for the text.

Usage

From source file:com.bangalore.barcamp.BCBUtils.java

public static void createActionBarOnActivity(final Activity activity, boolean isHome) {
    // ******** Start of Action Bar configuration
    ActionBar actionbar = (ActionBar) activity.findViewById(R.id.actionBar1);
    actionbar.setHomeLogo(R.drawable.home);
    actionbar.setHomeAction(new Action() {
        @Override/*from  w  w  w .  j  a v a  2 s.c  o m*/
        public void performAction(View view) {
            ((SlidingMenuActivity) activity).toggle();
        }

        @Override
        public int getDrawable() {
            return R.drawable.home;
        }
    });

    actionbar.setTitle(R.string.app_title_text);
    TextView logo = (TextView) activity.findViewById(R.id.actionbar_title);
    Shader textShader = new LinearGradient(0, 0, 0, logo.getHeight(), new int[] { Color.WHITE, 0xff999999 },
            null, TileMode.CLAMP);
    logo.getPaint().setShader(textShader);
    actionbar.setOnTitleClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });
    // ******** End of Action Bar configuration

}

From source file:cn.dreamtobe.emoji.ellipsize.helper.SpanEllipsizeEndHelper.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static CharSequence matchMaxWidth(SpannableString targetText, TextView textView) {
    if (targetText.length() <= 0) {
        return targetText;
    }// w  w  w . j a  va  2s. c  om

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        return targetText;
    }

    if (textView == null) {
        return targetText;
    }

    final int maxWidth = textView.getMaxWidth();

    if (maxWidth <= 0 || maxWidth >= Integer.MAX_VALUE) {
        return targetText;
    }

    if (textView.getEllipsize() != TextUtils.TruncateAt.END) {
        return targetText;
    }

    //TODO Multi-lines support
    if (textView.getMaxLines() != 1) {
        return targetText;
    }

    final String maxWidthKey = getMaxWidthKey(targetText, textView);
    SpannableString tmpText = SPAN_MAXWIDTH_CACHE.get(maxWidthKey);
    if (tmpText != null) {
        removeClickableSpan(tmpText);
        return tmpText;
    }

    TextPaint textPaint = textView.getPaint();
    if (textPaint == null) {
        return targetText;
    }

    final int totalWidth = (int) textPaint.measureText(targetText, 0, targetText.length());
    if (totalWidth <= maxWidth) {
        return targetText;
    }

    final long startTime = System.currentTimeMillis();
    // deal maxwitdh

    final int dotWidth = (int) textPaint.measureText("...");

    tmpText = targetText;

    int start = 0;
    int end = targetText.length();

    // targetX is maxWidth - "...".length
    int targetX = maxWidth - dotWidth;

    //dichotomy: get x most touch targetX
    int middle = targetText.length();
    int x = 0;
    while (start <= end) {
        // tx = targetX, tl = targetLength

        // width:  0           x
        // length: 0         middle           end
        //         -------------|-------------
        middle = (start + end) / 2;

        int emojiDraW = 0;
        int emojiStrW = 0;

        int emojiExcursion = 1;

        final Object[] tmpSpans = tmpText.getSpans(0, middle, Object.class);
        if (tmpSpans != null) {
            for (Object tmpSpan : tmpSpans) {
                final int tmpStart = tmpText.getSpanStart(tmpSpan);
                final int tmpEnd = tmpText.getSpanEnd(tmpSpan);

                //middle in (tmpStart, tmpEnd)
                if (tmpStart < middle && tmpEnd > middle) {
                    middle = tmpEnd;
                    emojiExcursion = tmpEnd - tmpStart;
                }
            }

            // TextPaint#measure do not attention span, so adjust by ourselves
            for (Object tmpSpan : tmpSpans) {
                final int tmpStart = tmpText.getSpanStart(tmpSpan);
                final int tmpEnd = tmpText.getSpanEnd(tmpSpan);

                // TODO support other span
                if (tmpStart < middle && tmpSpan instanceof ImageSpan) {
                    emojiDraW += ((ImageSpan) tmpSpan).getDrawable().getBounds().width();
                    emojiStrW += textPaint.measureText(tmpText, tmpStart, tmpEnd);
                }
            }

        }

        x = (int) textPaint.measureText(tmpText, 0, middle);
        x = x - emojiStrW + emojiDraW;

        //            x = (int) (textPaint.measureText(pureStr, 0, pureStr.length()) + emojiWidth);

        //            Log.d(TAG, String.format("targetX: %d, currentX: %d, currentLength: %d, totalLength: %d, emojiStrW[%d], emojiDraW[%d]", targetX, x, middle, targetText.length(), emojiStrW, emojiDraW));

        if (x > targetX) {
            // width:  0       tx        x
            // length: start   tl      middle         end
            //             ----|---------|-------------
            // TO:     start   |       *end
            //             ----|--------|--------------
            end = middle - emojiExcursion;
        } else if (x < targetX) {
            // width:  0               x       tx
            // length: start         middle    tl     end
            //           --------------|-------|------
            // TO:                      *start  |       end
            //           ---------------|------|------
            start = middle + 1;
        } else {
            break;
        }
    }

    // adjust x larger targetX
    while (x > targetX && middle > 0) {
        x = (int) textPaint.measureText(tmpText, 0, --middle);
    }

    // adjust x middle emoji span
    final Object[] ajustSpans = tmpText.getSpans(0, tmpText.length(), Object.class);
    for (Object adjustSpan : ajustSpans) {
        final int adjustStart = tmpText.getSpanStart(adjustSpan);
        final int adjustEnd = tmpText.getSpanEnd(adjustSpan);

        //[adjustStart, adjustEnd)
        if (middle >= adjustStart && middle < adjustEnd) {
            middle = adjustStart - 1;
            break;
        }
    }

    // finnal middle

    // sub sequence [0, middle + 1) & remove [middle +1, length] spans
    tmpText = (SpannableString) tmpText.subSequence(0, middle + 1);
    //        Log.d(TAG, String.format("sub Sequence[0, %d), [%s] to [%s]", middle + 1, targetText, tmpText));

    // add ...
    final SpannableString maxWidthSS = new SpannableString(tmpText + "...");

    final Object[] maxWidthSpans = tmpText.getSpans(0, tmpText.length(), Object.class);
    if (maxWidthSpans != null) {
        for (Object maxWidthSpan : maxWidthSpans) {
            final int mwSpanStart = tmpText.getSpanStart(maxWidthSpan);
            final int mwSpanEnd = tmpText.getSpanEnd(maxWidthSpan);
            final int mwSpanFlag = tmpText.getSpanFlags(maxWidth);

            maxWidthSS.setSpan(maxWidthSpan, mwSpanStart, mwSpanEnd, mwSpanFlag);
        }
    }

    targetText = maxWidthSS;

    SPAN_MAXWIDTH_CACHE.put(maxWidthKey, targetText);
    Log.d(TAG, String.format("deal maxWidth %d", System.currentTimeMillis() - startTime));

    return targetText;
}

From source file:com.pipit.agc.adapter.DayPickerAdapter.java

private void refitText(TextView txtv, int targetheight) {
    if (targetheight <= 0)
        return;//w  w  w.  ja v a  2s . c  o  m
    Paint mTestPaint = new Paint();
    mTestPaint.set(txtv.getPaint());
    float hi = 100;
    float lo = 2;
    final float threshold = 0.5f; // How close we have to be

    while ((hi - lo) > threshold) {
        float size = (hi + lo) / 2;
        mTestPaint.setTextSize(size);
        if (mTestPaint.measureText((String) txtv.getText()) >= targetheight)
            hi = size; // too big
        else
            lo = size; // too small
    }
    // Use lo so that we undershoot rather than overshoot
    txtv.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo);
}

From source file:com.dmsl.anyplace.SearchPOIActivity.java

private void handleIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        // get the search type
        mSearchType = (SearchTypes) intent.getSerializableExtra("searchType");
        if (mSearchType == null)
            finishSearch("No search type provided!", null);

        // get the query string
        final String query = intent.getStringExtra("query");
        double lat = intent.getDoubleExtra("lat", 0);
        double lng = intent.getDoubleExtra("lng", 0);

        AnyplaceSuggestionsTask mSuggestionsTask = new AnyplaceSuggestionsTask(
                new AnyplaceSuggestionsTask.AnyplaceSuggestionsListener() {

                    @Override/* w  w w  .j  a  va 2s.c om*/
                    public void onSuccess(String result, List<? extends IPoisClass> pois) {

                        // we have pois to query for a match
                        mQueriedPoisStr = new ArrayList<Spanned>();
                        mQueriedPois = pois;

                        // Display part of Description Text Only
                        // Make an approximation of available space based on map size
                        final int viewWidth = (int) (findViewById(R.id.txtResultsFound).getWidth() * 2);
                        View infoWindow = getLayoutInflater()
                                .inflate(R.layout.queried_pois_item_1_searchactivity, null);
                        TextView infoSnippet = (TextView) infoWindow;
                        TextPaint paint = infoSnippet.getPaint();

                        // Regular expression
                        // ?i ignore case
                        Pattern pattern = Pattern.compile(String.format("((?i)%s)", query));

                        for (IPoisClass pm : pois) {
                            String name = "", description = "";
                            Matcher m;
                            m = pattern.matcher(pm.name());
                            // Makes matched query bold using HTML format
                            // $1 returns the regular's expression outer parenthesis value
                            name = m.replaceAll("<b>$1</b>");

                            m = pattern.matcher(pm.description());
                            if (m.find()) {
                                // Makes matched query bold using HTML format
                                // $1 returns the regular's expression outer parenthesis value
                                int startIndex = m.start();
                                description = m.replaceAll("<b>$1</b>");
                                description = AndroidUtils.fillTextBox(paint, viewWidth, description,
                                        startIndex + 3);
                            }
                            mQueriedPoisStr.add(Html.fromHtml(name + "<br>" + description));
                        }

                        ArrayAdapter<Spanned> mAdapter = new ArrayAdapter<Spanned>(
                                // getBaseContext(), R.layout.queried_pois_item_1,
                                getBaseContext(), R.layout.queried_pois_item_1_searchactivity, mQueriedPoisStr);
                        lvResultPois.setAdapter(mAdapter);
                        txtResultsFound.setText("Results found [ " + mQueriedPoisStr.size() + " ]");

                    }

                    @Override
                    public void onErrorOrCancel(String result) {
                        // no pois exist
                        finishSearch("No Points of Interest exist!", null);
                    }

                    @Override
                    public void onUpdateStatus(String string, Cursor cursor) {
                        SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(),
                                R.layout.queried_pois_item_1_searchactivity, cursor,
                                new String[] { SearchManager.SUGGEST_COLUMN_TEXT_1 },
                                new int[] { android.R.id.text1 });
                        lvResultPois.setAdapter(adapter);
                        txtResultsFound.setText("Results found [ " + cursor.getCount() + " ]");
                    }

                }, this, mSearchType, new GeoPoint(lat, lng), query);
        mSuggestionsTask.execute();

    }
}

From source file:com.example.francis.examinationsystem.view.thirty.SlidingTabLayout.java

private void updateSelectedTitle(int positon) {
    final PagerAdapter adapter = mViewPager.getAdapter();
    for (int i = 0; i < adapter.getCount(); ++i) {
        final View tabView = mTabStrip.getChildAt(i);
        if (TextView.class.isInstance(tabView)) {
            TextView titleView = (TextView) tabView;
            titleView.getPaint().setFakeBoldText(true);
            boolean isSelected = i == positon;
            titleView.setTextColor(isSelected ? getResources().getColor(android.R.color.white)
                    : getResources().getColor(R.color.colorNormalText));
            titleView.setTextSize(isSelected ? 20 : TAB_VIEW_TEXT_SIZE_SP);
        }/*w  w  w. j  av  a  2  s  . c  o  m*/

    }
}

From source file:com.resonos.apps.library.tabviewpager.TabPageIndicator.java

/**
 * Does a bit of calculations to better measure the size of tabs.
 *  This is to fix a bug where text would occasionally get cut off.
 *///w ww .  j av a2s .com
private void doPreMeasure() {
    TabView tabView = (TabView) mInflater.inflate(R.layout.vpi__tab, null);
    TextView textView = (TextView) tabView.findViewById(android.R.id.text1);
    ImageView imageView = (ImageView) tabView.findViewById(R.id.img);
    mTextPaint = textView.getPaint();
    mTextPadding = textView.getTotalPaddingLeft() + textView.getTotalPaddingRight() + tabView.getPaddingLeft()
            + tabView.getPaddingRight();
    int mImagePadding = imageView.getPaddingLeft() + imageView.getPaddingRight();

    int t = 0;
    int count = getTitleProvider().getCount();
    mAllMinWidths = new int[count];
    String text;
    Drawable d;
    for (int i = 0; i < count; i++) {
        d = getTitleProvider().getIcon(i);
        text = getTitleProvider().getTitle(i);
        if (d != null) {
            mAllMinWidths[i] = d.getIntrinsicWidth() + mImagePadding;
        } else {
            StaticLayout layout = new StaticLayout(text, mTextPaint, MAX_TAB_WIDTH, Alignment.ALIGN_NORMAL,
                    1.0f, 0.0f, false);
            int w = (int) (layout.getLineWidth(0) + 1);
            mAllMinWidths[i] = mTextPadding + w;
        }
        if (getTitleProvider().isVisible(i))
            t += mAllMinWidths[i];
    }
    mTotalMinWidth = t;
}

From source file:com.viettel.dms.util.StatusNotificationHandler.java

/**
 * //from w w w .  j  av  a2s .c om
*  tao notification len status notification
*  @author: AnhND
*  @param appContext
*  @param activity
*  @return: void
*  @throws:
 */
private void postNotificationMessage(GlobalBaseActivity activity) {
    NotificationManager notificationManager = (NotificationManager) GlobalInfo.getInstance().getAppContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);
    int icon = R.drawable.icon_app_small;
    BitmapDrawable bd = (BitmapDrawable) GlobalInfo.getInstance().getAppContext().getResources()
            .getDrawable(icon);
    int iconWidth = bd.getBitmap().getWidth();
    CharSequence tickerText = getMessageNotify();
    long when = System.currentTimeMillis();
    // noi dung trong status bar khi keo xuong xem thong bao
    CharSequence contentText = Constants.STR_BLANK;
    contentText = getMessageNotify();

    int screenWidth = ((WindowManager) GlobalInfo.getInstance().getAppContext()
            .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
    screenWidth -= iconWidth;//for icon
    TextView textView = new TextView(GlobalInfo.getInstance().getAppContext());
    int count = tickerText.length();
    StringBuilder wrapTickerText = new StringBuilder();
    wrapTickerText.append(tickerText);
    while (count > 0) {
        if (count < tickerText.length()) {
            wrapTickerText.append("...");
        }
        float measuredWidth = textView.getPaint().measureText(wrapTickerText.toString());
        if (measuredWidth < screenWidth) {
            break;
        }
        count--;
        wrapTickerText.setLength(count);
    }
    Intent notificationIntent = initIntentMessage();
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
    //TamQP: fix bug _ phai truyen requestCode de phan biet PendingIntent lien tiep giong nhau
    int requestCode = (int) System.currentTimeMillis();
    PendingIntent contentIntent = PendingIntent.getActivity(GlobalInfo.getInstance().getAppContext(),
            requestCode, notificationIntent, 0);

    //       Notification notification = new Notification(icon, wrapTickerText, when);
    //       Intent notificationIntent = initIntentMessage();
    //       notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    //       //TamQP: fix bug _ phai truyen requestCode de phan biet PendingIntent lien tiep giong nhau
    //       int requestCode = (int) System.currentTimeMillis();
    //       PendingIntent contentIntent = PendingIntent.getActivity(GlobalInfo.getInstance().getAppContext(), requestCode, notificationIntent, 0);
    //
    //       notification.setLatestEventInfo(GlobalInfo.getInstance().getAppContext(), StringUtil.getString(R.string.app_name), contentText, contentIntent);
    //       notification.flags |= Notification.FLAG_AUTO_CANCEL;
    //       notification.defaults = Notification.DEFAULT_ALL;
    //
    //       notificationManager.cancel(NOTIFICATION_MESSAGE_ID);
    //       notificationManager.notify(NOTIFICATION_MESSAGE_ID, notification);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            GlobalInfo.getInstance().getAppContext());
    Notification notification = builder.setContentIntent(contentIntent).setSmallIcon(icon)
            .setTicker(contentText).setWhen(when).setAutoCancel(true)
            .setContentTitle(StringUtil.getString(R.string.app_name)).setContentText(contentText).build();
    notificationManager.cancel(NOTIFICATION_MESSAGE_ID);
    notificationManager.notify(NOTIFICATION_MESSAGE_ID, notification);

}

From source file:com.vuze.android.remote.activity.LoginActivity.java

private void setupGuideText(TextView tvLoginGuide) {
    AndroidUtilsUI.linkify(tvLoginGuide);
    CharSequence text = tvLoginGuide.getText();

    SpannableStringBuilder ss = new SpannableStringBuilder(text);
    String string = text.toString();

    new SpanBubbles().setSpanBubbles(ss, string, "|", tvLoginGuide.getPaint(),
            AndroidUtilsUI.getStyleColor(this, R.attr.login_text_color),
            AndroidUtilsUI.getStyleColor(this, R.attr.login_textbubble_color),
            AndroidUtilsUI.getStyleColor(this, R.attr.login_text_color));

    int indexOf = string.indexOf("@@");
    if (indexOf >= 0) {
        int style = ImageSpan.ALIGN_BASELINE;
        int newHeight = tvLoginGuide.getBaseline();
        if (newHeight <= 0) {
            newHeight = tvLoginGuide.getLineHeight();
            style = ImageSpan.ALIGN_BOTTOM;
            if (newHeight <= 0) {
                newHeight = 20;/*from   ww w .  j  a  v a  2 s .  co m*/
            }
        }
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.guide_icon);
        int oldWidth = drawable.getIntrinsicWidth();
        int oldHeight = drawable.getIntrinsicHeight();
        int newWidth = (oldHeight > 0) ? (oldWidth * newHeight) / oldHeight : newHeight;
        drawable.setBounds(0, 0, newWidth, newHeight);

        ImageSpan imageSpan = new ImageSpan(drawable, style);
        ss.setSpan(imageSpan, indexOf, indexOf + 2, 0);
    }

    tvLoginGuide.setText(ss);
}

From source file:us.shandian.blacklight.ui.main.MainActivity.java

@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
    if ((parent != mOther || position == 0) && mLastChoice != null) {
        mLastChoice.getPaint().setFakeBoldText(false);
        mLastChoice.invalidate();//from w w  w. jav  a  2 s.c  o m
    }

    if (mGroups != null && mGroups.getSize() > 0 && (parent != mOther || position != 1)) {
        getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        getActionBar().setDisplayShowTitleEnabled(true);
    }

    if (parent == mMy) {
        TextView tv = (TextView) view;
        tv.getPaint().setFakeBoldText(true);
        tv.invalidate();
        mLastChoice = tv;
        mNext = position;
        if (mFragments[position] != null) {
            tv.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        switchTo(position);
                    } catch (Exception e) {

                    }

                    if (position == 0 && mGroups != null && mGroups.getSize() > 0) {
                        getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
                        getActionBar().setDisplayShowTitleEnabled(false);
                        updateActionSpinner();
                    }
                }
            }, 400);
        }
    } else if (parent == mAtMe) {
        TextView tv = (TextView) view;
        tv.getPaint().setFakeBoldText(true);
        tv.invalidate();
        mLastChoice = tv;
        mNext = position + 4;
        if (mFragments[4 + position] != null) {
            tv.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        switchTo(4 + position);
                    } catch (Exception e) {

                    }
                }
            }, 400);
        }
    } else if (parent == mOther) {
        switch (position) {
        case 0: {
            mNext = 6;
            view.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        switchTo(6);
                    } catch (Exception e) {

                    }
                }
            }, 400);
            break;
        }
        case 1: {
            Intent i = new Intent();
            i.setAction(Intent.ACTION_MAIN);
            i.setClass(this, SettingsActivity.class);
            startActivity(i);
            break;
        }
        case 2: {
            mLoginCache.logout();
            Intent i = new Intent();
            i.setAction(Intent.ACTION_MAIN);
            i.setClass(this, EntryActivity.class);
            startActivity(i);
            finish();
            break;
        }
        }
    }

    mDrawer.closeDrawer(mDrawerGravity);
}

From source file:foam.starwisp.DrawableMap.java

public Marker AddText(final LatLng location, final String text, final int padding, final int fontSize,
        int colour) {
    Marker marker = null;/*  w  w w .ja  va2  s  .  co m*/

    final TextView textView = new TextView(m_Context);
    textView.setText(text);
    textView.setTextSize(fontSize);
    textView.setTypeface(m_Context.m_Typeface);

    final Paint paintText = textView.getPaint();

    final Rect boundsText = new Rect();
    paintText.getTextBounds(text, 0, textView.length(), boundsText);
    paintText.setTextAlign(Paint.Align.CENTER);

    final Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    final Bitmap bmpText = Bitmap.createBitmap(boundsText.width() + 2 * padding,
            boundsText.height() + 2 * padding, conf);

    final Canvas canvasText = new Canvas(bmpText);
    paintText.setColor(Color.BLACK);

    canvasText.drawText(text, (canvasText.getWidth() / 2) + 3,
            (canvasText.getHeight() - padding - boundsText.bottom) + 3, paintText);

    paintText.setColor(colour);

    canvasText.drawText(text, canvasText.getWidth() / 2, canvasText.getHeight() - padding - boundsText.bottom,
            paintText);

    final MarkerOptions markerOptions = new MarkerOptions().position(location)
            .icon(BitmapDescriptorFactory.fromBitmap(bmpText)).anchor(0.5f, 1);

    marker = map.addMarker(markerOptions);

    return marker;
}