1. 程式人生 > >TextView首行縮排效果(商品標籤)

TextView首行縮排效果(商品標籤)

這裡用兩個TextView分別展示商品標籤和商品描述資訊.
對商品描述資訊的TextView進行首行縮排處理.

通過LeadingMarginSpan.Standard(marginSpanSize, 0)設定首行縮排,這裡第一個引數為首行縮排的距離,第二個引數為其餘行縮排距離.

        /**
         * Constructor taking separate indents for the first and subsequent
         * lines.
         *
         * @param first the indent for the first line of the paragraph
         * @param
rest the indent for the remaining lines of the paragraph */
public Standard(int first, int rest) { mFirst = first; mRest = rest; }

首行縮排的距離為商品標籤顯示寬度.

      tvDes.setText(getSpannableString(label, description));
      tvLabel.setText(label);

    /**
     * 首行縮排的SpannableString
     *
     * @param
label 標籤資訊 * @param description 描述資訊 */
private SpannableString getSpannableString(String label, String description) { SpannableString spannableString = new SpannableString(description); int marginSpanSize = (int) (label.length() * getResources().getDimension(R.dimen.label_size) + dp2px(this
, 6));//文字寬度+ 背景padding4dp+間隔2dp LeadingMarginSpan leadingMarginSpan = new LeadingMarginSpan.Standard(marginSpanSize, 0);//僅首行縮排 spannableString.setSpan(leadingMarginSpan, 0, description.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); return spannableString; }

佈局檔案

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="horizontal"
  android:padding="10dp">
  <TextView
    android:id="@+id/des_tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="18sp"
    android:text=""
    />
  <TextView
    android:layout_marginTop="4dp"
    android:id="@+id/label_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="@dimen/label_size"
    android:textColor="#FFFFFF"
    android:background="@drawable/shape_bg_label"
    android:text=""
    />
</FrameLayout>

drawable/shape_bg_label

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
  <solid android:color="#FF0000"></solid>
  <corners android:radius="3dp"></corners>
  <padding
    android:bottom="0dp"
    android:left="2dp"
    android:right="2dp"
    android:top="0dp"></padding>
</shape>