简体   繁体   中英

Programmatic text wrapping in TextView

I'm working on a custom widget for my application to replicate the look of a Preference button for layouts. The issue is the 'summary' text won't wrap when it hits the right wall of the view. One of the goals I'm trying to keep is that this widget is completely made from java with no XML attributes.

Below is the code I'm using to create the text view.

public void setSummary(String summary) {
    if (!TextUtils.isEmpty(summary)) {
        if (mSummaryView == null) {
            mSummaryView = new TextView(mContext);
            mSummaryView.setTextSize(14);
            mSummaryView.setTextColor(mContext.getResources().getColor(
                                            android.R.color.tertiary_text_dark));
            addView(mSummaryView);
        }
        mSummaryView.setText(summary);
        mSummaryView.setVisibility(View.VISIBLE);
    } else {
        if (mSummaryView != null) {
            mSummaryView.setVisibility(View.GONE);
        }
    }
    mSummaryText = summary;
}

and here is the code I'm using to layout summary view

mSummaryView.layout(
            mPreferencePadding + mIconWidth,
            centerVertical + (mCombinedTextHeight / 2) - mSummaryHeight,
            width - mPreferencePadding,
            centerVertical + (mCombinedTextHeight / 2));

I've tried to add:

mSummaryView.setSingleLine(false);

along with quite a few other tricks but they all ended in the same way.

Set the max width of the TextView to the max size of the screen... you may want to consider padding as this will run the full size of the screen

// get the screen size
DisplayMetrics mDisplayMetrics = context.getResources().getDisplayMetrics();
// force view width to only be as wide as the screen
mSummaryView.setMaxWidth(mDisplayMetrics.widthPixels);

// could be a oneliner :P
mSummaryView.setMaxWidth((getContext().getResources().getDisplayMetrics()).widthPixels);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM