简体   繁体   English

TextView中的程序化文本换行

[英]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. 我要保留的目标之一是,此小部件完全由没有XML属性的Java制成。

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 TextView的最大宽度设置为屏幕的最大大小...您可能需要考虑填充,因为这会运行整个屏幕的大小

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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