下面列出了怎么用android.text.TextUtils.TruncateAt的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Creates a view into which preview text can be placed.
*/
private TextView createPreviewTextView(Context context) {
final LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(context);
textView.setLayoutParams(params);
textView.setSingleLine(true);
textView.setEllipsize(TruncateAt.MIDDLE);
textView.setGravity(Gravity.CENTER);
textView.setAlpha(0f);
// Manually propagate inherited layout direction.
textView.setLayoutDirection(mList.getLayoutDirection());
return textView;
}
@SuppressWarnings("deprecation")
private IndicatorPopup(View anchor, int popupColor, int popupSize, int textSize, int marginRight,
int popupAnimationStyle) {
super();
this.anchor = anchor;
this.popupSize = popupSize;
this.marginRight = marginRight;
this.bubbleView = new TextView(anchor.getContext());
bubbleView.setGravity(Gravity.CENTER);
bubbleView.setTextColor(Color.WHITE);
bubbleView.setSingleLine();
bubbleView.setBackgroundDrawable(new BubbleDrawable(popupColor));
bubbleView.setEllipsize(TruncateAt.END);
bubbleView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
this.popupWindow = new PopupWindow(bubbleView, popupSize, popupSize, false);
popupWindow.setAnimationStyle(popupAnimationStyle);
}
private void a() {
this.b = new TextView(this.a.F);
this.b.setTextColor(Color.rgb(255, 255, 255));
this.b.setTextSize(15.0f);
this.b.setShadowLayer(1.0f, 1.0f, 1.0f, Color.rgb(242, 211, 199));
this.b.setGravity(3);
this.b.setEllipsize(TruncateAt.END);
this.b.setIncludeFontPadding(false);
this.b.setSingleLine(true);
ViewGroup.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, -2);
layoutParams.weight = 1.0f;
layoutParams.leftMargin = this.a.a(4);
addView(this.b, layoutParams);
this.c = new Button(this.a.F);
this.c.setPadding(0, 0, 0, 0);
this.c.setTextSize(16.0f);
this.c.setTextColor(Color.rgb(255, 255, 255));
this.c.setShadowLayer(1.0f, 1.0f, 1.0f, Color.rgb(242, 211, 199));
this.c.setIncludeFontPadding(false);
this.c.setOnClickListener(new f(this.a, this.d.a));
layoutParams = new LinearLayout.LayoutParams(this.a.a(TaskGuide.p), this.a.a(TaskGuide.q));
layoutParams.leftMargin = this.a.a(2);
layoutParams.rightMargin = this.a.a(8);
addView(this.c, layoutParams);
}
private CharSequence getTruncatedText(int availWidth) {
final TextPaint paint = getPaint();
// Calculate the width the template takes.
final String emptyTemplate = String.format(mTemplate, "");
final float emptyTemplateWidth = paint.measureText(emptyTemplate);
// Calculate the available width for the content.
final float contentWidth = Math.max(availWidth - emptyTemplateWidth, 0.f);
// Ellipsize the content to the available width.
CharSequence clipped = TextUtils.ellipsize(mContent, paint, contentWidth, TruncateAt.END);
// Build the full string, which should fit within availWidth.
return String.format(mTemplate, clipped);
}
private CharSequence getTruncatedText(int availWidth) {
final TextPaint paint = getPaint();
// Calculate the width the template takes.
final String emptyTemplate = String.format(mTemplate, "");
final float emptyTemplateWidth = paint.measureText(emptyTemplate);
// Calculate the available width for the content.
final float contentWidth = Math.max(availWidth - emptyTemplateWidth, 0.f);
// Ellipsize the content to the available width.
CharSequence clipped = TextUtils.ellipsize(mContent, paint, contentWidth, TruncateAt.END);
// Build the full string, which should fit within availWidth.
return String.format(mTemplate, clipped);
}
private StaticLayout createStaticLayout(int maxLines, float availableWidth, boolean isRtl) {
StaticLayout textLayout = null;
try {
textLayout =
StaticLayoutBuilderCompat.obtain(text, textPaint, (int) availableWidth)
.setEllipsize(TruncateAt.END)
.setIsRtl(isRtl)
.setAlignment(ALIGN_NORMAL)
.setIncludePad(false)
.setMaxLines(maxLines)
.build();
} catch (StaticLayoutBuilderCompatException e) {
Log.e(TAG, e.getCause().getMessage(), e);
}
return checkNotNull(textLayout);
}
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int size = MeasureSpec.getSize(widthMeasureSpec);
final int mode = MeasureSpec.getMode(widthMeasureSpec);
if (!useSystemEmoji() &&
getEllipsize() == TruncateAt.END &&
!TextUtils.isEmpty(source) &&
(mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) &&
getPaint().breakText(source, 0, source.length()-1, true, size, null) != source.length())
{
needsEllipsizing = true;
FontMetricsInt font = getPaint().getFontMetricsInt();
super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(Math.abs(font.top - font.bottom), MeasureSpec.EXACTLY));
} else {
needsEllipsizing = false;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
public void setDisplayMode(int displayMode) {
// Displays the summary left text view in at most three lines if in focus mode,
// otherwise display it in a single line.
if (displayMode == DISPLAY_MODE_FOCUSED) {
setSummaryProperties(TruncateAt.END, false /* leftIsSingleLine */,
null /* rightTruncate */, false /* rightIsSingleLine */);
getSummaryLeftTextView().setMaxLines(3);
} else {
setSummaryProperties(TruncateAt.END, true /* leftIsSingleLine */,
null /* rightTruncate */, false /* rightIsSingleLine */);
getSummaryLeftTextView().setMaxLines(1);
}
super.setDisplayMode(displayMode);
}
private CharSequence getTruncatedText(int availWidth) {
final TextPaint paint = getPaint();
// Calculate the width the template takes.
final String emptyTemplate = String.format(mTemplate, "");
final float emptyTemplateWidth = paint.measureText(emptyTemplate);
// Calculate the available width for the content.
final float contentWidth = Math.max(availWidth - emptyTemplateWidth, 0.f);
// Ellipsize the content to the available width.
CharSequence clipped = TextUtils.ellipsize(mContent, paint, contentWidth, TruncateAt.END);
// Build the full string, which should fit within availWidth.
return String.format(mTemplate, clipped);
}
private TextView newTextView() {
TextView textView = new TextView(getContext());
textView.setLayoutParams(new LayoutParams(-1, -1, 16));
textView.setCompoundDrawablePadding(10);
textView.setPadding(10, 0, 0, 0);
textView.setGravity(16);
textView.setLines(2);
textView.setEllipsize(TruncateAt.END);
textView.setTextColor(Color.parseColor("#FFFFFF"));
textView.setTextSize(1, 14.0f);
return textView;
}
private View initTitleBar() {
RelativeLayout titleBar = new RelativeLayout(this);
titleBar.setLayoutParams(new LayoutParams(-1, ResourceManager.dp2px(this, 45)));
titleBar.setBackgroundDrawable(ResourceManager.getNinePatchDrawable(this, "weibosdk_navigationbar_background.9.png"));
this.mLeftBtn = new TextView(this);
this.mLeftBtn.setClickable(true);
this.mLeftBtn.setTextSize(2, 17.0f);
this.mLeftBtn.setTextColor(ResourceManager.createColorStateList(-32256, 1728020992));
this.mLeftBtn.setText(ResourceManager.getString(this, CANCEL_EN, "关闭", "关闭"));
RelativeLayout.LayoutParams leftBtnLp = new RelativeLayout.LayoutParams(-2, -2);
leftBtnLp.addRule(5);
leftBtnLp.addRule(15);
leftBtnLp.leftMargin = ResourceManager.dp2px(this, 10);
leftBtnLp.rightMargin = ResourceManager.dp2px(this, 10);
this.mLeftBtn.setLayoutParams(leftBtnLp);
titleBar.addView(this.mLeftBtn);
this.mTitleText = new TextView(this);
this.mTitleText.setTextSize(2, 18.0f);
this.mTitleText.setTextColor(-11382190);
this.mTitleText.setEllipsize(TruncateAt.END);
this.mTitleText.setSingleLine(true);
this.mTitleText.setGravity(17);
this.mTitleText.setMaxWidth(ResourceManager.dp2px(this, 160));
RelativeLayout.LayoutParams titleTextLy = new RelativeLayout.LayoutParams(-2, -2);
titleTextLy.addRule(13);
this.mTitleText.setLayoutParams(titleTextLy);
titleBar.addView(this.mTitleText);
return titleBar;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.item_doc_list, parent, false);
}
final ImageView iconMime = (ImageView) convertView.findViewById(R.id.icon_mime);
final TextView title = (TextView) convertView.findViewById(android.R.id.title);
final View line2 = convertView.findViewById(R.id.line2);
final DocumentStack stack = getItem(position);
iconMime.setImageDrawable(stack.root.loadIcon(context));
final Drawable crumb = ContextCompat.getDrawable(context, R.drawable.ic_breadcrumb_arrow);
crumb.setBounds(0, 0, crumb.getIntrinsicWidth(), crumb.getIntrinsicHeight());
final SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(stack.root.title);
for (int i = stack.size() - 2; i >= 0; i--) {
appendDrawable(builder, crumb);
builder.append(stack.get(i).displayName);
}
title.setText(builder);
title.setEllipsize(TruncateAt.MIDDLE);
if (line2 != null) line2.setVisibility(View.GONE);
return convertView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.item_doc_list, parent, false);
}
final ImageView iconMime = (ImageView) convertView.findViewById(R.id.icon_mime);
final TextView title = (TextView) convertView.findViewById(android.R.id.title);
final View line2 = convertView.findViewById(R.id.line2);
final DocumentStack stack = getItem(position);
iconMime.setImageDrawable(stack.root.loadIcon(context));
final Drawable crumb = ContextCompat.getDrawable(context, R.drawable.ic_breadcrumb_arrow);
crumb.setBounds(0, 0, crumb.getIntrinsicWidth(), crumb.getIntrinsicHeight());
final SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(stack.root.title);
for (int i = stack.size() - 2; i >= 0; i--) {
appendDrawable(builder, crumb);
builder.append(stack.get(i).displayName);
}
title.setText(builder);
title.setEllipsize(TruncateAt.MIDDLE);
if (line2 != null) line2.setVisibility(View.GONE);
return convertView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.item_doc_list, parent, false);
}
final ImageView iconMime = (ImageView) convertView.findViewById(R.id.icon_mime);
final TextView title = (TextView) convertView.findViewById(android.R.id.title);
final View line2 = convertView.findViewById(R.id.line2);
final DocumentStack stack = getItem(position);
iconMime.setImageDrawable(stack.root.loadIcon(context));
final Drawable crumb = ContextCompat.getDrawable(context, R.drawable.ic_breadcrumb_arrow);
crumb.setBounds(0, 0, crumb.getIntrinsicWidth(), crumb.getIntrinsicHeight());
final SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(stack.root.title);
for (int i = stack.size() - 2; i >= 0; i--) {
appendDrawable(builder, crumb);
builder.append(stack.get(i).displayName);
}
title.setText(builder);
title.setEllipsize(TruncateAt.MIDDLE);
if (line2 != null) line2.setVisibility(View.GONE);
return convertView;
}
/**
* Sets how the summary text should be displayed.
*
* @param leftTruncate How to truncate the left summary text. Set to null to clear.
* @param rightTruncate How to truncate the right summary text. Set to null to clear.
*/
public void setSummaryProperties(@Nullable TruncateAt leftTruncate, boolean leftIsSingleLine,
@Nullable TruncateAt rightTruncate, boolean rightIsSingleLine) {
mSummaryLeftTextView.setEllipsize(leftTruncate);
mSummaryLeftTextView.setSingleLine(leftIsSingleLine);
mSummaryRightTextView.setEllipsize(rightTruncate);
mSummaryRightTextView.setSingleLine(rightIsSingleLine);
}
/**
* Sets how the summary text should be displayed.
*
* @param leftTruncate How to truncate the left summary text. Set to null to clear.
* @param rightTruncate How to truncate the right summary text. Set to null to clear.
*/
public void setSummaryProperties(@Nullable TruncateAt leftTruncate, boolean leftIsSingleLine,
@Nullable TruncateAt rightTruncate, boolean rightIsSingleLine) {
mSummaryLeftTextView.setEllipsize(leftTruncate);
mSummaryLeftTextView.setSingleLine(leftIsSingleLine);
mSummaryRightTextView.setEllipsize(rightTruncate);
mSummaryRightTextView.setSingleLine(rightIsSingleLine);
}
/**
* Sets how the extra texts should be displayed.
*
* @param textsTruncate How to truncate the extra texts. Set the element to null to clear.
* @param textsAreSingleLine Whether the extra texts should be displayed in a single line.
*/
public void setExtraTextsProperties(
TruncateAt[] textsTruncate, boolean[] textsAreSingleLine) {
assert textsTruncate.length == mExtraTextViews.length;
assert textsAreSingleLine.length == mExtraTextViews.length;
for (int i = 0; i < mExtraTextViews.length; i++) {
mExtraTextViews[i].setEllipsize(textsTruncate[i]);
mExtraTextViews[i].setSingleLine(textsAreSingleLine[i]);
}
}
/**
* Sets sensible default values for {@link MaterialButton} child of this group, set child to
* {@code checkable}, and set internal checked change listener for this child.
*
* @param buttonChild {@link MaterialButton} child to set up to be added to this {@link
* MaterialButtonToggleGroup}
*/
private void setupButtonChild(@NonNull MaterialButton buttonChild) {
buttonChild.setMaxLines(1);
buttonChild.setEllipsize(TruncateAt.END);
buttonChild.setCheckable(true);
buttonChild.addOnCheckedChangeListener(checkedStateTracker);
buttonChild.setOnPressedChangeListenerInternal(pressedStateTracker);
// Enables surface layer drawing for semi-opaque strokes
buttonChild.setShouldDrawSurfaceColorStroke(true);
}
@Override
public void setEllipsize(TruncateAt where) {
if (chipDrawable == null) {
return;
}
if (where == TruncateAt.MARQUEE) {
throw new UnsupportedOperationException("Text within a chip are not allowed to scroll.");
}
super.setEllipsize(where);
if (chipDrawable != null) {
chipDrawable.setEllipsize(where);
}
}
@Config(minSdk = LOLLIPOP, maxSdk = VERSION_CODES.P)
@Test
public void createStaticLayout_withMaxLines_LongString() throws Exception {
int maxLines = 3;
StaticLayout staticLayout =
StaticLayoutBuilderCompat.obtain(LONG_STRING, new TextPaint(), 100)
.setAlignment(Alignment.ALIGN_NORMAL)
.setIncludePad(true)
.setEllipsize(TruncateAt.END)
.setMaxLines(maxLines)
.build();
assertThat(staticLayout).isNotNull();
}
public static CharSequence ellipsize(@Nullable CharSequence text, @NonNull TextView view) {
if (TextUtils.isEmpty(text) || view.getWidth() == 0 || view.getEllipsize() != TruncateAt.END) {
return text;
} else {
return TextUtils.ellipsize(text,
view.getPaint(),
view.getWidth() - view.getPaddingRight() - view.getPaddingLeft(),
TruncateAt.END);
}
}
/**
* Set the alignment mode of the specified TextView with the desired align
* mode from preferences.
*
* See @array/audio_title_alignment_values
*
* @param alignMode Align mode as read from preferences
* @param t Reference to the textview
*/
public static void setAlignModeByPref(int alignMode, TextView t) {
if(alignMode == 1)
t.setEllipsize(TruncateAt.END);
else if(alignMode == 2)
t.setEllipsize(TruncateAt.START);
else if(alignMode == 3) {
t.setEllipsize(TruncateAt.MARQUEE);
t.setMarqueeRepeatLimit(-1);
t.setSelected(true);
}
}
/**
* Sets how the summary text should be displayed.
*
* @param leftTruncate How to truncate the left summary text. Set to null to clear.
* @param leftIsSingleLine Whether the left summary text should be a single line.
* @param rightTruncate How to truncate the right summary text. Set to null to clear.
* @param rightIsSingleLine Whether the right summary text should be a single line.
*/
public void setSummaryProperties(@Nullable TruncateAt leftTruncate, boolean leftIsSingleLine,
@Nullable TruncateAt rightTruncate, boolean rightIsSingleLine) {
mSummaryLeftTextView.setEllipsize(leftTruncate);
mSummaryLeftTextView.setSingleLine(leftIsSingleLine);
mSummaryRightTextView.setEllipsize(rightTruncate);
mSummaryRightTextView.setSingleLine(rightIsSingleLine);
}
/**
* Updates the View to account for the new {@link ShippingSummaryInformation} being passed
* in.
*/
public void update(ShippingSummaryInformation info) {
String selectedShippingName = info.getSelectedShippingAddressLabel();
String selectedShippingAddress = info.getSelectedShippingAddressSublabel();
String selectedShippingPhone = info.getSelectedShippingAddressTertiaryLabel();
String selectedShippingOptionLabel = info.getSelectedShippingOptionLabel();
// Display the summary in a single line.
setSummaryProperties(TruncateAt.END, true /* leftIsSingleLine */,
null /* rightTruncate */, false /* rightIsSingleLine */);
if (selectedShippingAddress == null || selectedShippingOptionLabel == null) {
ApiCompatibilityUtils.setTextAppearance(
getSummaryLeftTextView(), R.style.PaymentsUiSectionDescriptiveText);
SectionUiUtils.showSectionSummaryInTextViewInSingeLine(getContext(),
info.getShippingAddressSectionInfo(), getSummaryLeftTextView());
} else {
// Show the shipping name in the summary section.
setSummaryText(selectedShippingName, null);
// Show the shipping address, phone and option below the summary.
setExtraTextsProperties(
new TruncateAt[] {TruncateAt.MIDDLE, TruncateAt.END, TruncateAt.END},
new boolean[] {true, true, true});
setExtraTexts(new String[] {selectedShippingAddress, selectedShippingPhone,
selectedShippingOptionLabel});
}
}
/**
* Sets how the extra texts should be displayed.
*
* @param textsTruncate How to truncate the extra texts. Set the element to null to clear.
* @param textsAreSingleLine Whether the extra texts should be displayed in a single line.
*/
private void setExtraTextsProperties(
TruncateAt[] textsTruncate, boolean[] textsAreSingleLine) {
assert textsTruncate.length == mExtraTextViews.length;
assert textsAreSingleLine.length == mExtraTextViews.length;
for (int i = 0; i < mExtraTextViews.length; i++) {
mExtraTextViews[i].setEllipsize(textsTruncate[i]);
mExtraTextViews[i].setSingleLine(textsAreSingleLine[i]);
}
}
private RadioButton createRadioView() {
RadioButton mRadioButton = new RadioButton(getContext(), null, mRadioStyle > 0 ? mRadioStyle : android.R.attr.radioButtonStyle);
if (mRadioStyle == 0) {
mRadioButton.setGravity(Gravity.CENTER);
mRadioButton.setEllipsize(TruncateAt.END);
}
if (mTextColor != null)
mRadioButton.setTextColor(mTextColor);
if (textSize > 0)
mRadioButton.setTextSize(textSize);
return mRadioButton;
}
/**
* Returns the value of the enum {@link TruncateAt}, which corresponds to a specific value.
*
* @param value
* The value
* @return The value of the enum {@link TruncateAt}, which corresponds to the given value
*/
private TruncateAt parseEllipsize(final int value) {
switch (value) {
case ELLIPSIZE_START_VALUE:
return TruncateAt.START;
case ELLIPSIZE_MIDDLE_VALUE:
return TruncateAt.MIDDLE;
case ELLIPSIZE_END_VALUE:
return TruncateAt.END;
case ELLIPSIZE_MARQUEE_VALUE:
return TruncateAt.MARQUEE;
default:
return TruncateAt.END;
}
}
private void addTemporaryTab(){
for (int i = 0; i < 3; i++) {
CharSequence title = null;
if (i == 0)
title = "TAB ONE";
else if (i == 1)
title = "TAB TWO";
else if (i == 2)
title = "TAB THREE";
CheckedTextView tv = new CheckedTextView(getContext());
tv.setCheckMarkDrawable(null);
tv.setText(title);
tv.setGravity(Gravity.CENTER);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tv.setTextAlignment(CheckedTextView.TEXT_ALIGNMENT_GRAVITY);
}
tv.setTextAppearance(getContext(), mTextAppearance);
tv.setSingleLine(true);
tv.setEllipsize(TruncateAt.END);
tv.setTag(i);
tv.setChecked(i == 0);
if(mMode == MODE_SCROLL){
tv.setPadding(mTabPadding, 0, mTabPadding, 0);
mTabContainer.addView(tv, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
else if(mMode == MODE_FIXED){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
params.weight = 1f;
mTabContainer.addView(tv, params);
}
}
}
protected void initLayout() {
context = getContext();
view = LayoutInflater.from(context).inflate(R.layout.item_editext_del,
null);
lefText = (TextView) view.findViewById(R.id.leftText);
middleText = (EditText) view.findViewById(R.id.middleText);
rightText = (TextView) view.findViewById(R.id.rightText);
rightImg = (ImageView) view.findViewById(R.id.right_img);
middleText.setSingleLine(true);
middleText.setEllipsize(TruncateAt.END);
middleText.setClickable(true);
addListener();
addView(view);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = new TextView(parent.getContext());
view.setText(String.format("%s: %sx%s", "Video", sizes.get(position).width, sizes.get(position).height));
view.setEllipsize(TruncateAt.END);
view.setPadding(16, 16, 16, 16);
return view;
}