Example usage for android.text TextPaint measureText

List of usage examples for android.text TextPaint measureText

Introduction

In this page you can find the example usage for android.text TextPaint measureText.

Prototype

public float measureText(String text) 

Source Link

Document

Return the width of the text.

Usage

From source file:com.jecelyin.editor.v2.core.text.TextUtils.java

/**
 * Returns the original text if it fits in the specified width
 * given the properties of the specified Paint,
 * or, if it does not fit, a copy with ellipsis character added
 * at the specified edge or center.// w  w w . j av a2s  .  c  o m
 * If <code>preserveLength</code> is specified, the returned copy
 * will be padded with zero-width spaces to preserve the original
 * length and offsets instead of truncating.
 * If <code>callback</code> is non-null, it will be called to
 * report the start and end of the ellipsized range.
 *
 * @hide
 */
public static CharSequence ellipsize(CharSequence text, TextPaint paint, float avail, TruncateAt where,
        boolean preserveLength, EllipsizeCallback callback, TextDirectionHeuristic textDir, String ellipsis) {

    int len = text.length();

    MeasuredText mt = MeasuredText.obtain();
    try {
        float width = setPara(mt, paint, text, 0, text.length(), textDir);

        if (width <= avail) {
            if (callback != null) {
                callback.ellipsized(0, 0);
            }

            return text;
        }

        // XXX assumes ellipsis string does not require shaping and
        // is unaffected by style
        float ellipsiswid = paint.measureText(ellipsis);
        avail -= ellipsiswid;

        int left = 0;
        int right = len;
        if (avail < 0) {
            // it all goes
        } else if (where == TruncateAt.START) {
            right = len - mt.breakText(len, false, avail);
        } else if (where == TruncateAt.END || where == TruncateAt.END_SMALL) {
            left = mt.breakText(len, true, avail);
        } else {
            right = len - mt.breakText(len, false, avail / 2);
            avail -= mt.measure(right, len);
            left = mt.breakText(right, true, avail);
        }

        if (callback != null) {
            callback.ellipsized(left, right);
        }

        char[] buf = mt.mChars;
        Spanned sp = text instanceof Spanned ? (Spanned) text : null;

        int remaining = len - (right - left);
        if (preserveLength) {
            if (remaining > 0) { // else eliminate the ellipsis too
                buf[left++] = ellipsis.charAt(0);
            }
            for (int i = left; i < right; i++) {
                buf[i] = ZWNBS_CHAR;
            }
            String s = new String(buf, 0, len);
            if (sp == null) {
                return s;
            }
            SpannableString ss = new SpannableString(s);
            copySpansFrom(sp, 0, len, Object.class, ss, 0);
            return ss;
        }

        if (remaining == 0) {
            return "";
        }

        if (sp == null) {
            StringBuilder sb = new StringBuilder(remaining + ellipsis.length());
            sb.append(buf, 0, left);
            sb.append(ellipsis);
            sb.append(buf, right, len - right);
            return sb.toString();
        }

        SpannableStringBuilder ssb = new SpannableStringBuilder();
        ssb.append(text, 0, left);
        ssb.append(ellipsis);
        ssb.append(text, right, len);
        return ssb;
    } finally {
        MeasuredText.recycle(mt);
    }
}

From source file:org.totschnig.myexpenses.activity.ExpenseEdit.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.one_expense);

    mDateFormat = android.text.format.DateFormat.getDateFormat(this);
    mTimeFormat = android.text.format.DateFormat.getTimeFormat(this);

    setupToolbar();/*w ww .  j ava  2s  . c  o  m*/
    mManager = getSupportLoaderManager();
    //we enable it only after accountcursor has been loaded, preventing NPE when user clicks on it early
    configTypeButton();
    mTypeButton.setEnabled(false);
    mCommentText = (EditText) findViewById(R.id.Comment);
    mTitleText = (EditText) findViewById(R.id.Title);
    mReferenceNumberText = (EditText) findViewById(R.id.Number);
    mDateButton = (Button) findViewById(R.id.DateButton);
    mAttachPictureButton = (ImageView) findViewById(R.id.AttachImage);
    mPictureViewContainer = (FrameLayout) findViewById(R.id.picture_container);
    mTimeButton = (Button) findViewById(R.id.TimeButton);
    mPayeeLabel = (TextView) findViewById(R.id.PayeeLabel);
    mPayeeText = (AutoCompleteTextView) findViewById(R.id.Payee);
    mTransferAmountText = (AmountEditText) findViewById(R.id.TranferAmount);
    mExchangeRate1Text = (AmountEditText) findViewById(R.id.ExchangeRate_1);
    mExchangeRate1Text.setFractionDigits(EXCHANGE_RATE_FRACTION_DIGITS);
    mExchangeRate1Text.addTextChangedListener(new LinkedExchangeRateTextWatchter(true));
    mExchangeRate2Text = (AmountEditText) findViewById(R.id.ExchangeRate_2);
    mExchangeRate2Text.setFractionDigits(EXCHANGE_RATE_FRACTION_DIGITS);
    mExchangeRate2Text.addTextChangedListener(new LinkedExchangeRateTextWatchter(false));

    mPayeeAdapter = new SimpleCursorAdapter(this, R.layout.support_simple_spinner_dropdown_item, null,
            new String[] { KEY_PAYEE_NAME }, new int[] { android.R.id.text1 }, 0);
    mPayeeText.setAdapter(mPayeeAdapter);
    mPayeeAdapter.setFilterQueryProvider(new FilterQueryProvider() {
        @SuppressLint("NewApi")
        public Cursor runQuery(CharSequence str) {
            if (str == null) {
                return null;
            }
            String search = Utils.esacapeSqlLikeExpression(Utils.normalize(str.toString()));
            //we accept the string at the beginning of a word
            String selection = KEY_PAYEE_NAME_NORMALIZED + " LIKE ? OR " + KEY_PAYEE_NAME_NORMALIZED
                    + " LIKE ? OR " + KEY_PAYEE_NAME_NORMALIZED + " LIKE ?";
            String[] selectArgs = { search + "%", "% " + search + "%", "%." + search + "%" };
            return getContentResolver().query(TransactionProvider.PAYEES_URI, new String[] { KEY_ROWID,
                    KEY_PAYEE_NAME,
                    "(SELECT max(" + KEY_ROWID + ") FROM " + TABLE_TRANSACTIONS + " WHERE " + WHERE_NOT_SPLIT
                            + " AND " + KEY_PAYEEID + " = " + TABLE_PAYEES + "." + KEY_ROWID + ")" },
                    selection, selectArgs, null);
        }
    });

    mPayeeAdapter.setCursorToStringConverter(new CursorToStringConverter() {
        public CharSequence convertToString(Cursor cur) {
            return cur.getString(1);
        }
    });
    mPayeeText.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Cursor c = (Cursor) mPayeeAdapter.getItem(position);
            if (c.moveToPosition(position)) {
                mTransaction.updatePayeeWithId(c.getString(1), c.getLong(0));
                if (mNewInstance && mTransaction != null
                        && !(mTransaction instanceof Template || mTransaction instanceof SplitTransaction)) {
                    //moveToPosition should not be necessary,
                    //but has been reported to not be positioned correctly on samsung GT-I8190N
                    if (!c.isNull(2)) {
                        if (PrefKey.AUTO_FILL_HINT_SHOWN.getBoolean(false)) {
                            if (PrefKey.AUTO_FILL.getBoolean(true)) {
                                startAutoFill(c.getLong(2));
                            }
                        } else {
                            Bundle b = new Bundle();
                            b.putLong(KEY_ROWID, c.getLong(2));
                            b.putInt(ConfirmationDialogFragment.KEY_TITLE, R.string.dialog_title_information);
                            b.putString(ConfirmationDialogFragment.KEY_MESSAGE,
                                    getString(R.string.hint_auto_fill));
                            b.putInt(ConfirmationDialogFragment.KEY_COMMAND_POSITIVE, R.id.AUTO_FILL_COMMAND);
                            b.putString(ConfirmationDialogFragment.KEY_PREFKEY,
                                    PrefKey.AUTO_FILL_HINT_SHOWN.getKey());
                            b.putInt(ConfirmationDialogFragment.KEY_POSITIVE_BUTTON_LABEL, R.string.yes);
                            b.putInt(ConfirmationDialogFragment.KEY_NEGATIVE_BUTTON_LABEL, R.string.no);
                            ConfirmationDialogFragment.newInstance(b).show(getSupportFragmentManager(),
                                    "AUTO_FILL_HINT");
                        }
                    }
                }
            }
        }
    });

    mCategoryButton = (Button) findViewById(R.id.Category);
    mPlanButton = (Button) findViewById(R.id.Plan);
    mMethodSpinner = (Spinner) findViewById(R.id.Method);
    mAccountSpinner = new SpinnerHelper(findViewById(R.id.Account));
    mTransferAccountSpinner = new SpinnerHelper(findViewById(R.id.TransferAccount));
    mTransferAccountSpinner.setOnItemSelectedListener(this);
    mStatusSpinner = new SpinnerHelper(findViewById(R.id.Status));
    mReccurenceSpinner = new SpinnerHelper(findViewById(R.id.Recurrence));
    mPlanToggleButton = (ToggleButton) findViewById(R.id.PlanExecutionAutomatic);
    TextPaint paint = mPlanToggleButton.getPaint();
    int automatic = (int) paint.measureText(getString(R.string.plan_automatic));
    int manual = (int) paint.measureText(getString(R.string.plan_manual));
    mPlanToggleButton.setWidth((automatic > manual ? automatic : manual) + +mPlanToggleButton.getPaddingLeft()
            + mPlanToggleButton.getPaddingRight());

    mRowId = Utils.getFromExtra(getIntent().getExtras(), KEY_ROWID, 0);

    //upon orientation change stored in instance state, since new splitTransactions are immediately persisted to DB
    if (savedInstanceState != null) {
        mSavedInstance = true;
        mRowId = savedInstanceState.getLong(KEY_ROWID);
        mPictureUri = savedInstanceState.getParcelable(KEY_PICTURE_URI);
        mPictureUriTemp = savedInstanceState.getParcelable(KEY_PICTURE_URI_TMP);
        setPicture();

        mCalendar = (Calendar) savedInstanceState.getSerializable(KEY_CALENDAR);
        mLabel = savedInstanceState.getString(KEY_LABEL);
        if ((mCatId = savedInstanceState.getLong(KEY_CATID)) == 0L) {
            mCatId = null;
        }
        if ((mMethodId = savedInstanceState.getLong(KEY_METHODID)) == 0L)
            mMethodId = null;
        if ((mAccountId = savedInstanceState.getLong(KEY_ACCOUNTID)) == 0L) {
            mAccountId = null;
        } else {
            //once user has selected account, we no longer want
            //the passed in KEY_CURRENCY to override it in onLoadFinished
            getIntent().removeExtra(KEY_CURRENCY);
        }
        if ((mTransferAccountId = savedInstanceState.getLong(KEY_TRANSFER_ACCOUNT)) == 0L)
            mTransferAccountId = null;
    }
    mTemplateId = getIntent().getLongExtra(KEY_TEMPLATEID, 0);
    //were we called from a notification
    int notificationId = getIntent().getIntExtra(MyApplication.KEY_NOTIFICATION_ID, 0);
    if (notificationId > 0) {
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(notificationId);
    }

    CrStatusAdapter sAdapter = new CrStatusAdapter(this) {

        @Override
        public boolean isEnabled(int position) {
            //if the transaction is reconciled, the status can not be changed
            //otherwise only unreconciled and cleared can be set
            return mTransaction != null && mTransaction.crStatus != CrStatus.RECONCILED
                    && position != CrStatus.RECONCILED.ordinal();
        }
    };
    mStatusSpinner.setAdapter(sAdapter);

    //1. fetch the transaction or create a new instance
    if (mRowId != 0 || mTemplateId != 0) {
        mNewInstance = false;
        int taskId;
        Serializable extra = null;
        Long objectId;
        if (mRowId != 0) {
            taskId = TaskExecutionFragment.TASK_INSTANTIATE_TRANSACTION;
            //if called with extra KEY_CLONE, we ask the task to clone, but no longer after orientation change
            extra = getIntent().getBooleanExtra(KEY_CLONE, false) && savedInstanceState == null;
            objectId = mRowId;
        } else {
            objectId = mTemplateId;
            //are we editing the template or instantiating a new one
            if ((mPlanInstanceId = getIntent().getLongExtra(KEY_INSTANCEID, 0)) != 0L) {
                taskId = TaskExecutionFragment.TASK_INSTANTIATE_TRANSACTION_FROM_TEMPLATE;
                mPlanInstanceDate = getIntent().getLongExtra(KEY_DATE, 0);
                mRecordTemplateWidget = getIntent().getBooleanExtra(AbstractWidget.EXTRA_START_FROM_WIDGET,
                        false) && !ContribFeature.TEMPLATE_WIDGET.hasAccess();
            } else {
                taskId = TaskExecutionFragment.TASK_INSTANTIATE_TEMPLATE;
            }
        }
        FragmentManager fm = getSupportFragmentManager();
        if (fm.findFragmentByTag(ProtectionDelegate.ASYNC_TAG) == null) {
            startTaskExecution(taskId, new Long[] { objectId }, extra, R.string.progress_dialog_loading);
        }
    } else {
        mOperationType = getIntent().getIntExtra(MyApplication.KEY_OPERATION_TYPE, MyExpenses.TYPE_TRANSACTION);
        if (!isValidType(mOperationType)) {
            mOperationType = MyExpenses.TYPE_TRANSACTION;
        }
        if (mOperationType == MyExpenses.TYPE_SPLIT && !ContribFeature.SPLIT_TRANSACTION.hasAccess()
                && ContribFeature.SPLIT_TRANSACTION.usagesLeft() < 1) {
            Toast.makeText(this, ContribFeature.SPLIT_TRANSACTION.buildRequiresString(this), Toast.LENGTH_LONG)
                    .show();
            finish();
            return;
        }
        final Long parentId = getIntent().getLongExtra(KEY_PARENTID, 0);
        final boolean isNewTemplate = getIntent().getBooleanExtra(KEY_NEW_TEMPLATE, false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        View spinner = findViewById(R.id.OperationType);
        mOperationTypeSpinner = new SpinnerHelper(spinner);
        spinner.setVisibility(View.VISIBLE);
        List<Integer> allowedOperationTypes = new ArrayList<>();
        allowedOperationTypes.add(MyExpenses.TYPE_TRANSACTION);
        allowedOperationTypes.add(MyExpenses.TYPE_TRANSFER);
        if (!isNewTemplate && parentId == 0) {
            allowedOperationTypes.add(MyExpenses.TYPE_SPLIT);
        }
        mOperationTypeAdapter = new OperationTypeAdapter(this, allowedOperationTypes, isNewTemplate,
                parentId != 0);
        mOperationTypeSpinner.setAdapter(mOperationTypeAdapter);
        resetOperationType();
        mOperationTypeSpinner.setOnItemSelectedListener(this);
        Long accountId = getIntent().getLongExtra(KEY_ACCOUNTID, 0);
        if (isNewTemplate) {
            mTransaction = Template.getTypedNewInstance(mOperationType, accountId);
        } else {
            switch (mOperationType) {
            case MyExpenses.TYPE_TRANSACTION:
                if (accountId == 0L) {
                    accountId = MyApplication.getInstance().getSettings()
                            .getLong(PREFKEY_TRANSACTION_LAST_ACCOUNT_FROM_WIDGET, 0L);
                }
                mTransaction = parentId == 0L ? Transaction.getNewInstance(accountId)
                        : SplitPartCategory.getNewInstance(accountId, parentId);
                break;
            case MyExpenses.TYPE_TRANSFER:
                Long transfer_account = 0L;
                if (accountId == 0L) {
                    accountId = MyApplication.getInstance().getSettings()
                            .getLong(PREFKEY_TRANSFER_LAST_ACCOUNT_FROM_WIDGET, 0L);
                    transfer_account = MyApplication.getInstance().getSettings()
                            .getLong(PREFKEY_TRANSFER_LAST_TRANSFER_ACCOUNT_FROM_WIDGET, 0L);
                }
                mTransaction = parentId == 0L ? Transfer.getNewInstance(accountId, transfer_account)
                        : SplitPartTransfer.getNewInstance(accountId, parentId, transfer_account);
                break;
            case MyExpenses.TYPE_SPLIT:
                if (accountId == 0L) {
                    accountId = MyApplication.getInstance().getSettings()
                            .getLong(PREFKEY_SPLIT_LAST_ACCOUNT_FROM_WIDGET, 0L);
                }
                mTransaction = SplitTransaction.getNewInstance(accountId);
                //Split transactions are returned persisted to db and already have an id
                if (mTransaction != null) {
                    mRowId = mTransaction.getId();
                }
                break;
            }
        }
        if (mTransaction == null) {
            String errMsg = "Error instantiating transaction for account " + accountId;
            AcraHelper.report(new IllegalStateException(errMsg), "Extras", getIntent().getExtras().toString());
            Toast.makeText(this, errMsg, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        if (!mSavedInstance) {
            //processing data from user switching operation type
            Transaction cached = (Transaction) getIntent().getSerializableExtra(KEY_CACHED_DATA);
            if (cached != null) {
                mTransaction.accountId = cached.accountId;
                mCalendar.setTime(cached.getDate());
                mPictureUri = getIntent().getParcelableExtra(KEY_CACHED_PICTURE_URI);
                setPicture();
                mTransaction.methodId = cached.methodId;
            }
        }
        setup();
    }
}

From source file:com.android.ex.chips.RecipientEditTextView.java

private MoreImageSpan createMoreSpan(final int count) {
    final String moreText = String.format(mMoreItem.getText().toString(), count);
    final TextPaint morePaint = new TextPaint(getPaint());
    morePaint.setTextSize(mMoreItem.getTextSize());
    morePaint.setColor(mMoreItem.getCurrentTextColor());
    final int width = (int) morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
            + mMoreItem.getPaddingRight();
    final int height = getLineHeight();
    final Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(drawable);
    int adjustedHeight = height;
    final Layout layout = getLayout();
    if (layout != null)
        adjustedHeight -= layout.getLineDescent(0);
    canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
    final Drawable result = new BitmapDrawable(getResources(), drawable);
    result.setBounds(0, 0, width, height);
    return new MoreImageSpan(result);
}