Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自訂 View 樣式外掛化:TypedArray 與 declare-styleable 實戰

編輯:關於 Android 程式設計

寫自訂 View 時,若希望它像系統控制項一樣可以透過 XML 屬性調整外觀,就必須認識 TypedArray。舉例來說,想讓自訂的展開/收合 TextView 能配置展開圖示、收合圖示、以及折疊時最少顯示幾行,靠的就是這套機制。

先來看效果,預設折疊狀態:

點擊後展開:

1. 自訂 View 類別

這裡讓 ExpandTextView 繼承 LinearLayout,內部塞一個 TextView 加一個 ImageView,並在 onMeasure 中依行數決定要不要顯示展開圖示:

 /** * @title ExpandTextView * @description 可擴展TextView,可以通過設置ExpandTextViewStyle來自定義展開圖片、收起圖片和最小展示的行數 */ public class ExpandTextView extends LinearLayout implements OnClickListener { /** * 默認最少展示的行數 */ private int defaultMinLines; /** * 是否展開 */ private boolean mCollapsed = true; /** * 是否重新布局 */ private boolean mRelayout = false; private View expandView; private TextView expandText; private ImageView expandImg; private Drawable mExpandDrawable; private Drawable mCollapseDrawable; public ExpandTextView(Context context) { this(context, null); } public ExpandTextView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { expandView = LayoutInflater.from(getContext()).inflate( R.layout.pt__expand_textview, null); expandText = (TextView) expandView.findViewById(R.id.expand_text); expandText.setOnClickListener(this); expandImg = (ImageView) expandView.findViewById(R.id.expand_img); expandImg.setOnClickListener(this); TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ExpandTextViewStyle); // 自定義圖片資源 mExpandDrawable = getResources().getDrawable( a.getResourceId(R.styleable.ExpandTextViewStyle_expand, R.drawable.pt__ic_expand)); expandImg.setBackgroundDrawable(mExpandDrawable); mCollapseDrawable = getResources().getDrawable( a.getResourceId(R.styleable.ExpandTextViewStyle_collapse, R.drawable.pt__ic_collapse)); // 自定義最小行數 defaultMinLines = a.getInt( R.styleable.ExpandTextViewStyle_default_min_lines, 2); a.recycle(); LinearLayout.LayoutParams params = new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); params.gravity = Gravity.CENTER; addView(expandView, params); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (!mRelayout) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } mRelayout = false; expandText.setMaxLines(Integer.MAX_VALUE); expandImg.setVisibility(View.GONE); super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (expandText.getLineCount() <= defaultMinLines) { return; } if (mCollapsed) { expandText.setMaxLines(defaultMinLines); } expandImg.setVisibility(View.VISIBLE); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public void setText(CharSequence text) { mRelayout = true; expandText.setText(text); } public void setText(int resId) { this.setText(getContext().getString(resId)); } @Override public void onClick(View view) { if (expandImg.getVisibility() != View.VISIBLE) { return; } mCollapsed = !mCollapsed; expandImg.setBackgroundDrawable(mCollapsed ? mExpandDrawable : mCollapseDrawable); expandText .setMaxLines(mCollapsed ? defaultMinLines : Integer.MAX_VALUE); } } 

2. 在 attrs.xml 中宣告屬性

放在 res/values/attrs.xml,用 declare-styleable 把相關屬性打包成一個樣式集合:

 <resources> <!-- ******************************可擴展ExpandTextView樣式******************************* --> <declare-styleable name="ExpandTextViewStyle"> <!-- 展開圖片 --> <attr name="expand" format="reference" /> <!-- 關閉圖片 --> <attr name="collapse" format="reference" /> <!-- 最小行數 --> <attr name="default_min_lines" format="integer" /> </declare-styleable> </resources> 

3. 在 styles.xml 中預設一組樣式(可選)

 <!-- 可擴展ExpandTextView樣式 --> <style name="ExpandTextViewStyle"> <item name="expand">@drawable/pt__ic_expand</item> <item name="collapse">@drawable/pt__ic_collapse</item> <item name="default_min_lines">3</item> </style> 

4. 布局檔中使用

記得先在根節點宣告自訂命名空間,前綴 custom 對應到 app 的 package 路徑:

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:custom="https://schemas.android.com/apk/res/com.example.typedarraytest" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" > <com.example.typedarraytest.ExpandTextView android:id="@+id/expand_text_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="8dp" custom:default_min_lines="2" /> </RelativeLayout> 

實作步驟濃縮

1. 先寫好 attrs.xml,宣告 declare-styleable 與各 attr 的型別;

2. 在自訂 View 的建構流程中取得屬性,關鍵就這幾行:

 TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ExpandTextViewStyle); // 自定義圖片資源 mExpandDrawable = getResources().getDrawable( a.getResourceId(R.styleable.ExpandTextViewStyle_expand, R.drawable.pt__ic_expand)); expandImg.setBackgroundDrawable(mExpandDrawable); mCollapseDrawable = getResources().getDrawable( a.getResourceId(R.styleable.ExpandTextViewStyle_collapse, R.drawable.pt__ic_collapse)); // 自定義最小行數 defaultMinLines = a.getInt( R.styleable.ExpandTextViewStyle_default_min_lines, 2); a.recycle(); 

3. 屬性可以寫在 style.xml 中集中管理,也可以直接在布局檔逐個覆寫,例如 custom:default_min_lines="2"。命名空間格式為 xmlns:自訂關鍵字="https://schemas.android.com/apk/res/你的包名"。

兩個務必養成習慣的細節:屬性取完一定要呼叫 a.recycle(),否則會造成資源洩漏;另外 obtainStyledAttributes 的第二個參數是 R.styleable 中的陣列,不是單一屬性,這也是很多人第一次用會卡住的地方。

感謝閱讀,希望對大家有幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved