摘要:Android - 自訂屬性 - IconTitleLayout
繼上一篇,訂定元件,
但偶爾我想要用 xml設定屬性,就可以省下很多寫Code的時間。
這時要自訂屬性怎麼做?
參考下面這篇文章
http://julianshen.blogspot.tw/2013/06/android-view.html
實作了,
要準備一個attrs.xml 內容如下
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="IconTitleLayout">
<attr name="title" format="string"/>
<attr name="icon" format="integer" />
</declare-styleable>
</resources>
相對的Class改寫如下
package com.tomlai.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tomlai.demo.app.R;
public class IconTitleLayout extends LinearLayout {
ImageView mImageView ;
TextView mTextView;
public IconTitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.widget_icon_title_layout, this );
mImageView = (ImageView)this.findViewById(R.id.icon);
mTextView = (TextView)this.findViewById(R.id.title);
initFromAttributes(context, attrs);
}
private void initFromAttributes(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IconTitleLayout);
for (int i = 0; i < a.getIndexCount(); i++) {
int attr = a.getIndex(i);
String title = "";
switch (attr) {
case R.styleable.IconTitleLayout_title:
title = a.getString(attr);
this.setTitle(title);
break;
case R.styleable.IconTitleLayout_icon:
Drawable drawable = a.getDrawable(R.styleable.IconTitleLayout_icon);
if (drawable != null)
mImageView.setImageDrawable(drawable);
break;
}
}
a.recycle();
}
public void setTitle(String title) {
mTextView.setText(title);
}
public String getTitle() {
return mTextView.getText().toString();
}
}
在acitivty_main.xml裡的IconTitleLayout ,要改寫如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000"
xmlns:iconlayout="http://schemas.android.com/apk/res-auto">
<com.tomlai.widget.IconTitleLayout
android:id="@+id/icon_title_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
iconlayout:title="Icon Title 2"
iconlayout:icon="@drawable/selector_icon" >
</com.tomlai.widget.IconTitleLayout>
</LinearLayout>
關於命名空間xmlns,好像就隨便命好像就可以了,我直接命iconlayout
xmlns:iconlayout="http://schemas.android.com/apk/res-auto"
就可以直接使用
iconlayout:title的方式,使用attrs.xml裡所定義的title