androidattrs
A. android中怎麼在View構造的attrs中拿到android給的屬性
//Android原生的屬性,都是提供方法可以獲得的,當然也可以通過
attrs獲得,而自定義的屬性獲得值方式如下,當然原生的也是一樣,只需要把attr name該成系統的。
一、 首先要在res/values目錄下建立一個attrs.xml(名字可以自己定義)的文件,並在此文件中增加對控制項的屬性的定義.其xml文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="my_text_view">
<attr name="text_size" format="float"></attr>
<attr name="text_color" format="color"></attr>
<attr name="text_back_ground" format="color|reference"></attr>
</declare-styleable>
</resources>
在這里,需要補充attrs屬性的相關知識,即Attr屬性是如何在XML中定義的,自定義屬性的Value值可以有10種類型以及其類型的組合值,其具體使用方法如下:
1. reference:參考某一資源ID。
(1)屬性定義:
<declare-styleable name = "名稱">
<attr name = "background" format = "reference" />
</declare-styleable>
(2)屬性使用:
<ImageView
android:layout_width = "42dip"
android:layout_height = "42dip"
android:background = "@drawable/圖片ID"
/>
2. color:顏色值。
(1)屬性定義:
<declare-styleable name = "名稱">
<attr name = "textColor" format = "color" />
</declare-styleable>
(2)屬性使用:
<TextView
android:layout_width = "42dip"
android:layout_height = "42dip"
android:textColor = "#00FF00"
/>
3. boolean:布爾值。
(1)屬性定義:
<declare-styleable name = "名稱">
<attr name = "focusable" format = "boolean" />
</declare-styleable>
(2)屬性使用:
<Button
android:layout_width = "42dip"
android:layout_height = "42dip"
android:focusable = "true"
/>
4. dimension:尺寸值。
(1)屬性定義:
<declare-styleable name = "名稱">
<attr name = "layout_width" format = "dimension" />
</declare-styleable>
(2)屬性使用:
<Button
android:layout_width = "42dip"
android:layout_height = "42dip"
/>
5. float:浮點值。
(1)屬性定義:
<declare-styleable name = "AlphaAnimation">
<attr name = "fromAlpha" format = "float" />
<attr name = "toAlpha" format = "float" />
</declare-styleable>
(2)屬性使用:
<alpha
android:fromAlpha = "1.0"
android:toAlpha = "0.7"
/>
6. integer:整型值。
(1)屬性定義:
<declare-styleable name = "AnimatedRotateDrawable">
<attr name = "visible" />
<attr name = "frameDuration" format="integer" />
<attr name = "framesCount" format="integer" />
<attr name = "pivotX" />
<attr name = "pivotY" />
<attr name = "drawable" />
</declare-styleable>
(2)屬性使用:
<animated-rotate
xmlns:android = "http://schemas.android.com/apk/res/android"
android:drawable = "@drawable/圖片ID"
android:pivotX = "50%"
android:pivotY = "50%"
android:framesCount = "12"
android:frameDuration = "100"
/>
7. string:字元串。
(1)屬性定義:
<declare-styleable name = "MapView">
<attr name = "apiKey" format = "string" />
</declare-styleable>
(2)屬性使用:
<com.google.android.maps.MapView
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:apiKey = "_bc_g"
/>
8. fraction:百分數。
(1)屬性定義:
<declare-styleable name="RotateDrawable">
<attr name = "visible" />
<attr name = "fromDegrees" format = "float" />
<attr name = "toDegrees" format = "float" />
<attr name = "pivotX" format = "fraction" />
<attr name = "pivotY" format = "fraction" />
<attr name = "drawable" />
</declare-styleable>
(2)屬性使用:
<rotate
xmlns:android = "http://schemas.android.com/apk/res/android"
android:interpolator = "@anim/動畫ID"
android:fromDegrees = "0"
android:toDegrees = "360"
android:pivotX = "200%"
android:pivotY = "300%"
android:ration = "5000"
android:repeatMode = "restart"
android:repeatCount = "infinite"
/>
9. enum:枚舉值。
(1)屬性定義:
<declare-styleable name="名稱">
<attr name="orientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
</declare-styleable>
(2)屬性使用:
<LinearLayout
xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
>
</LinearLayout>
10. flag:位或運算。
(1)屬性定義:
<declare-styleable name="名稱">
<attr name="windowSoftInputMode">
<flag name = "stateUnspecified" value = "0" />
<flag name = "stateUnchanged" value = "1" />
<flag name = "stateHidden" value = "2" />
<flag name = "stateAlwaysHidden" value = "3" />
<flag name = "stateVisible" value = "4" />
<flag name = "stateAlwaysVisible" value = "5" />
<flag name = "adjustUnspecified" value = "0x00" />
<flag name = "adjustResize" value = "0x10" />
<flag name = "adjustPan" value = "0x20" />
<flag name = "adjustNothing" value = "0x30" />
</attr>
</declare-styleable>
(2)屬性使用:
<activity
android:name = ".StyleAndThemeActivity"
android:label = "@string/app_name"
android:windowSoftInputMode = "stateUnspecified | stateUnchanged|stateHidden">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
注意:
屬性定義時可以指定多種類型值。
(1)屬性定義:
<declare-styleable name = "名稱">
<attr name = "background" format = "reference|color" />
</declare-styleable>
(2)屬性使用:
<ImageView
android:layout_width = "42dip"
android:layout_height = "42dip"
android:background = "@drawable/圖片ID|#00FF00"
/>
二、接下來實現自定義View的類,其中下面的構造方法是重點,在代碼中獲取自定義屬性,其代碼如下:
package com.example.CustomAttr;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
/**
* Created with IntelliJ IDEA.
* User: wen.nan
* Date: 13-9-28
* Time: 下午10:00
* To change this template use File | Settings | File Templates.
*/
public class CustomTextView extends TextView {
private TypedArray mTypedArray;
private Paint mPaint;
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
inial(context,attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
inial(context,attrs);
}
private void inial(Context context,AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.my_text_view);
float textsize = typedArray.getFloat(R.styleable.my_text_view_text_size,14) ;
int textColor = typedArray.getColor(R.styleable.my_text_view_text_color,0xFFFFFF) ;
int bgColor = typedArray.getColor(R.styleable.my_text_view_text_back_ground,0xFFFFFF) ;
super.setTextColor(textColor);
super.setTextSize(textsize);
super.setBackgroundColor(bgColor);
typedArray.recycle();
}
}
三、接下來在XML布局中引用自定義View控制項,其XML代碼如下:
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res/com.example.CustomAttr"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.example.CustomAttr.CustomTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MainActivity"
app:text_size ="20"
app:text_color ="#00FF00"
app:text_back_ground="#ffffff"
/>
</LinearLayout>
注意上面XML中代碼: xmlns:app = "http://schemas.android.com/apk/res/com.example.CustomAttr",是自定義的app命名空間,res後面是應用程序包名,然後可以直接使用app:text_size,等屬性,其值類型要和attrs.xml定義的屬性Value值相對應。
四、總結:
注意該例子中是使用app:text_size = "20 和app:text_color="#00FF00定義TextView的顏色和textView的字體大小,而不是使用系統的屬性android:textsize等。該例子中只是起到拋磚引玉的作用,你可以自定義其他屬性,來實現你想要的自定義View效果。
B. 急問!!!Android中如何獲取或者定義AttributeSet參數
Android中如何獲取AttributeSet參數的方法如下:
1.Attributeset自定義控制項和其他的控制項一樣,應該寫成一個類,而這個類的屬性是是有自己來決定的.
2.首先要在res/values目錄下建立一個attrs.xml的文件,並在此文件中增加對控制項的屬性的定義.
3.使用AttributeSet來完成控制項類的構造函數,並在構造函數中將自定義控制項類中變數與attrs.xml中的屬性連接起來.
4.在自定義控制項類中使用這些已經連接的屬性變數.
5.將自定義的控制項類定義到布局用的xml文件中去.
6.在界面中生成此自定義控制項類對象,並加以使用.
C. android中如何在xml文件中增加屬性
好的設置方式往往是數據驅動的,通過數據控制代碼的運行,便於代碼的維護和修改。在android中增中自定義的xml屬性, 可以把數據存儲在xml文件中,然後在代碼中取出這些屬性的值。分為以下幾步:
1. 在attrs.xml文件中定義屬性的類型,即字元串還是數值如下:
2.在xml 文件中指定譔屬性的值。如下:
android:key="tiltSensitivity"
android:defaultValue="50"
android:title="@string/preference_tilt_sensitivity"
android:summary="@string/preference_tilt_sensitivity_summary"
replica:maxText="@string/preference_tilt_max"
replica:minText="@string/preference_tilt_min"
android:persistent="true"
android:dependency="enableTiltControls"/>
3.在代碼中讀取值,方法如下:
public SliderPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.SliderPreference, defStyle, 0);
mMinText = a.getString(R.styleable.SliderPreference_minText);
D. android自定義控制項怎麼用
一、控制項自定義屬性介紹
以下示例中代碼均在values/attrs.xml 中定義,屬性均可隨意命名。
1. reference:參考某一資源ID。
示例:
<declare-styleable name = "名稱">
<attr name = "background" format = "reference" />
<attr name = "src" format = "reference" />
</declare-styleable>
2. color:顏色值。
示例:
<declare-styleable name = "名稱">
<attr name = "textColor" format = "color" />
</declare-styleable>
3. boolean:布爾值。
示例:
<declare-styleable name = "名稱">
<attr name = "focusable" format = "boolean" />
</declare-styleable>
4. dimension:尺寸值。
示例:
<declare-styleable name = "名稱">
<attr name = "layout_width" format = "dimension" />
</declare-styleable>
5. float:浮點值。
示例:
<declare-styleable name = "名稱">
<attr name = "fromAlpha" format = "float" />
<attr name = "toAlpha" format = "float" />
</declare-styleable>
6. integer:整型值。
示例:
<declare-styleable name = "名稱">
<attr name = "frameDuration" format="integer" />
<attr name = "framesCount" format="integer" />
</declare-styleable>
7. string:字元串。
示例:
<declare-styleable name = "名稱">
<attr name = "text" format = "string" />
</declare-styleable>
8. fraction:百分數。
示例:
<declare-styleable name="名稱">
<attr name = "pivotX" format = "fraction" />
<attr name = "pivotY" format = "fraction" />
</declare-styleable>
9. enum:枚舉值。
示例:
<declare-styleable name="名稱">
<attr name="orientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
</declare-styleable>
10. flag:位或運算。
示例:
<declare-styleable name="名稱">
<attr name="windowSoftInputMode">
<flag name = "stateUnspecified" value = "0" />
<flag name = "stateUnchanged" value = "1" />
<flag name = "stateHidden" value = "2" />
<flag name = "stateAlwaysHidden" value = "3" />
</attr>
</declare-styleable>
11.多類型。
示例:
<declare-styleable name = "名稱">
<attr name = "background" format = "reference|color" />
</declare-styleable>
二、屬性的使用以及自定義控制項的實現
1、構思控制項的組成元素,思考所需自定義的屬性。
比如:我要做一個 <帶陰影的按鈕,按鈕正下方有文字說明>(類似9宮格按鈕)
新建values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="custom_view">
<attr name="custom_id" format="integer" />
<attr name="src" format="reference" />
<attr name="background" format="reference" />
<attr name="text" format="string" />
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
以上,所定義為custom_view,custom_id為按鈕id,src為按鈕,background為陰影背景,text為按鈕說明,textColor為字體顏色,textSize為字體大小。
2、怎麼自定義控制項呢,怎麼使用這些屬性呢?話不多說請看代碼,CustomView :
package com.nanlus.custom;
import com.nanlus.custom.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomView extends FrameLayout implements OnClickListener {
private CustomListener customListener = null;
private Drawable mSrc = null, mBackground = null;
private String mText = "";
private int mTextColor = 0;
private float mTextSize = 20;
private int mCustomId = 0;
private ImageView mBackgroundView = null;
private ImageButton mButtonView = null;
private TextView mTextView = null;
private LayoutParams mParams = null;
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.custom_view);
mSrc = a.getDrawable(R.styleable.custom_view_src);
mBackground = a.getDrawable(R.styleable.custom_view_background);
mText = a.getString(R.styleable.custom_view_text);
mTextColor = a.getColor(R.styleable.custom_view_textColor,
Color.WHITE);
mTextSize = a.getDimension(R.styleable.custom_view_textSize, 20);
mCustomId = a.getInt(R.styleable.custom_view_custom_id, 0);
mTextView = new TextView(context);
mTextView.setTextSize(mTextSize);
mTextView.setTextColor(mTextColor);
mTextView.setText(mText);
mTextView.setGravity(Gravity.CENTER);
mTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mButtonView = new ImageButton(context);
mButtonView.setImageDrawable(mSrc);
mButtonView.setBackgroundDrawable(null);
mButtonView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mButtonView.setOnClickListener(this);
mBackgroundView = new ImageView(context);
mBackgroundView.setImageDrawable(mBackground);
mBackgroundView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(mBackgroundView);
addView(mButtonView);
addView(mTextView);
this.setOnClickListener(this);
a.recycle();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mParams = (LayoutParams) mButtonView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
mButtonView.setLayoutParams(mParams);
}
mParams = (LayoutParams) mBackgroundView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
mBackgroundView.setLayoutParams(mParams);
}
mParams = (LayoutParams) mTextView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
mTextView.setLayoutParams(mParams);
}
}
public void setCustomListener(CustomListener l) {
customListener = l;
}
@Override
public void onClick(View v) {
if (customListener != null) {
customListener.onCuscomClick(v, mCustomId);
}
}
public interface CustomListener {
void onCuscomClick(View v, int custom_id);
}
}
代碼很簡單,就不多說,下面來看看我們的CustomView是怎麼用的,請看:
3、自定義控制項的使用
話不多說,請看代碼,main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:nanlus="http://schemas.android.com/apk/res/com.nanlus.custom"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="horizontal" >
<com.nanlus.custom.CustomView
android:id="@+id/custom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
nanlus:background="@drawable/background"
nanlus:custom_id="1"
nanlus:src="@drawable/style_button"
nanlus:text="按鈕1" >
</com.nanlus.custom.CustomView>
</LinearLayout>
</RelativeLayout>
在這里需要解釋一下,
xmlns:nanlus="http://schemas.android.com/apk/res/com.nanlus.custom"
nanlus為在xml中的前綴,com.nanlus.custom為包名
4、在Activity中,直接上代碼
package com.nanlus.custom;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nanlus.BaseActivity;
import com.nanlus.custom.R;
import com.nanlus.custom.CustomView.CustomListener;
public class CustomActivity extends BaseActivity implements CustomListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((CustomView) this.findViewById(R.id.custom1)).setCustomListener(this);
}
@Override
public void onCuscomClick(View v, int custom_id) {
switch (custom_id) {
case 1:
Toast.makeText(this, "hello !!!", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
E. android 怎麼動態給進度條自定義屬性attrs動態的賦值
自定義屬性的話,你可以自己自定義一個view,實現類似於進度條的控制項
F. Android自定義控制項,為何要用super將參數context和attrs傳遞給父類的構造函數
這個問題很基礎的吧,面向對象有參構造函數,super,this,建議去一些培訓機構發的視頻,我不是打廣告的哈,b站上就有免費的,我估計你有些東西自己還沒明白
首先如果android開發,自定義View必須直接繼承或者間接繼承View,ViewGroup,
現在想想如果你不加super,那麼你的構造方法等於說什麼有實際意義的代碼都沒有被系統調用
,也就是說你寫的自定義View就是一個空殼子,只不過名字叫做XXX View,構造方法裡面裡面是要初始化數據的,你沒有加super就是你沒有用父類的方法來初始化數據,當然你也可以自己初始化數據,不過沒人這么干,因為麻煩,或者說浪費你自己的時間,畢竟父類已經把一些簡單的初始化代碼已經有了,你自己寫不是給自己找不自在嗎
G. android studio attrs.xml在哪兒
1. 定義一些自定義屬性
建立一個屬性xml文件: values/attrs.xml, 內容如下:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<!-- the relation between the icon and text. -->
<attr name="relation">
<enum name="icon_left" value="0" />
<enum name="icon_right" value="1" />
<enum name="icon_above" value="2" />
<enum name="icon_below" value="3" />
</attr>
<skip />
<declare-styleable name="IconText">
<attr name="relation" />
<attr name="icon" format="reference" />
<attr name="text" format="string" />
<attr name="text_size" format="dimension" />
<attr name="text_color" format="integer" />
<attr name="space" format="dimension" />
</declare-styleable>
H. android 怎麼在代碼中獲取控制項的屬性值
如果是自定義的控制項可以用一下代碼TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyToggleBtn);// 由attrs 獲得 TypeArray,
如果是系統自帶的控制項,通常控制項點get會有對應的獲取屬性值的方法,如textView.getHeight,不過有些方法如margin,就要通過layoutparam去獲取設置
I. android 自定義圖片選擇器,怎麼篩選圖片
偽代碼如下:
private boolean flag;
public void onClick(View v){
if(flag){
mImageView.setImageResource(R.drawable.xx1);
}else{
mImageView.setImageResource(R.drawable.xx2);
}
flag = !flag;
}123456789123456789
筆者連上面的代碼知道寫出來那為什麼還要去自定義一個ImageView了?
具體需求:兩個ImageView之間實現單選效果
我們試想下,目前兩個ImageView通過上面的代碼可能還好,只要在不同的事件中做出不同的判斷就好了,但如果一但ImageView增多了了?
A:你不知道用 RadioGroup+RadioButton 啊!
B:是哦!我現在去試下。
……
B:不行啊,雖然RadioButton可以實現,但不好做適配,我為RadioButton設置Drawable,不能居中,而且不能隨著RadioButton的大小改變而改變,資源圖片是多大就多大,顯示區域不夠就不能完全顯示出來。
A:…?,額,是嗎?這樣啊!那我們就自定義一個ImageView來實現吧!
B:為什麼是自定義ImageView?而不是自定義RadioButton?
A:自定義RadioButton實現ImageView的src屬性比較復雜(等著正在看這博客的大神實現),而自定義ImageView來實現單選的屬性比較好實現。
B:那怎麼實現了?
A:看代碼,代碼如下:
attrs.xml <為自定義ImageView添加兩個屬性>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SelectorImageView">
<attr name="selector_src" format="reference"/>//選中的src圖片屬性
<attr name="checked" format="boolean"/>
</declare-styleable>
</resources>12345671234567
Class - SelectorImageView<此類實現了Checkable介面,這里沒什麼特殊功能,而只是利用此介面中的方法而已,不實現我們也可以自己寫>
public class SelectorImageView extends ImageView implements Checkable {
private boolean isChecked;
private Drawable mSelectorDrawable;
private Drawable mDrawable;
public SelectorImageView(Context context) {
this(context, null);
}
public SelectorImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SelectorImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
/**獲取默認屬性src的Drawable並用成員變數保存*/
mDrawable = getDrawable();
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SelectorImageView);
/**獲取自定義屬性selector_src的Drawable並用成員變數保存*/
Drawable d = a.getDrawable(R.styleable.SelectorImageView_selector_src);
mSelectorDrawable = d;
/**獲取自定義屬性checked的值並用成員變數保存*/
isChecked = a.getBoolean(R.styleable.SelectorImageView_checked, false);
setChecked(isChecked);
if (d != null && isChecked) {
/**如果在布局中設置了selector_src與checked = true,我們就要設置ImageView的圖片為mSelectorDrawable */
setImageDrawable(d);
}
a.recycle();
}
@Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
}
@Override
public void setChecked(boolean checked) {
this.isChecked = checked;
}
@Override
public boolean isChecked() {
return isChecked;
}
@Override
public void toggle() {
/**此處依據是否選中來設置不同的圖片*/
if (isChecked()) {
setImageDrawable(mSelectorDrawable);
} else {
setImageDrawable(mDrawable);
}
}
public void toggle(boolean checked){
/**外部通過調用此方法傳入checked參數,然後把值傳入給setChecked()方法改變當前的選中狀態*/
setChecked(checked);
toggle();
}
}
layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.qjay.adf.widget.SelectorImageView
android:id="@+id/iv"
android:layout_width="100dp"
android:layout_height="100dp"
app:selector_src="@mipmap/checked"
android:src="@mipmap/no_checked"/>
</LinearLayout>12345678910111234567891011
Activity Code
public class MainActivity extends Activity {
private SelectorImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (SelectorImageView) findViewById(R.id.iv);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
iv.toggle(!iv.isChecked());
}
});
}
}
J. 從源碼中淺析Android中怎麼利用attrs和styles定義控制項
1.attrs.xml:
我們知道Android的源碼中有attrs.xml這個文件,這個文件實際上定義了所有的控制項的屬性,就是我們在布局文件中設置的各類屬性
你可以找到attrs.xml這個文件,打開它,全選,右鍵->Show In->OutLine。可以看到整個文件的解構
我們大概可以看出裡面是Android中的各種屬性的聲明,比如textStyle這個屬性是這樣定義的:
java代碼
<!-- Default text typeface style. -->
<attr name="textStyle">
<flag name="normal" value="0" />
<flag name="bold" value="1" />
<flag name="italic" value="2" />
</attr>
那麼現在你知道,我們在寫android:textStyle的時候為什麼會出現normal,bold和italic這3個東西了吧,就是定義在這個地方。
再看看textColor:
Java代碼
<!-- Color of text (usually same as colorForeground). -->
<attr name="textColor" format="reference|color" />
format的意思是說:這個textColor可以以兩種方式設置,要麼是關聯一個值,要麼是直接設置一個顏色的RGB值,這個不難理解,因為我們可以平時也這樣做過。
也就是說我們平時在布局文件中所使用的各類控制項的屬性都定義在這裡面,那麼這個文件,除了定義這些屬性外還定義了各種具體的組件,比如TextView,Button,SeekBar等所具有的各種特有的屬性
比如SeekBar:
Java代碼
<declare-styleable name="SeekBar">
<!-- Draws the thumb on a seekbar. -->
<attr name="thumb" format="reference" />
<!-- An offset for the thumb that allows it to extend out of the range of the track. -->
<attr name="thumbOffset" format="dimension" />
</declare-styleable>
也許你會問SeekBar的background,等屬性怎麼沒有看到?這是因為Android中幾乎所有的組件都是從View中繼承下來的,SeekBar自然也不例外,而background這個屬性幾乎每個控制項都有,因此被定義到了View中,你可以在declare-styleable:View中找到它。
總結下,也就是說attrs.xml這個文件定義了布局文件中的各種屬性attr:***,以及每種控制項特有的屬性declare-styleable:***
2.styles.xml:
剛才的attrs.xml定義的是組件的屬性,現在要說的style則是針對這些屬性所設置的值,一些默認的值。
這個是SeekBar的樣式,我們可以看到,這裡面設置了一個SeekBar的默認的樣式,即為attrs.xml文件中的各種屬性設置初始值
Java代碼
<style name="Widget.SeekBar">
<item name="android:indeterminateOnly">false</item>
<item name="android:progressDrawable">@android:drawable/progress_horizontal</item>
<item name="android:indeterminateDrawable">@android:drawable/progress_horizontal</item>
<item name="android:minHeight">20dip</item>
<item name="android:maxHeight">20dip</item>
<item name="android:thumb">@android:drawable/seek_thumb</item>
<item name="android:thumbOffset">8dip</item>
<item name="android:focusable">true</item>
</style>
這個是Button的樣式:
Java代碼
<style name="Widget.Button">
<item name="android:background">@android:drawable/btn_default</item>
<item name="android:focusable">true</item>
<item name="android:clickable">true</item>
<item name="android:textAppearance">?android:attr/textAppearanceSmallInverse</item>
<item name="android:textColor">@android:color/primary_text_light</item>
<item name="android:gravity">center_vertical|center_horizontal</item>
</style>
有了屬性和值,但是這些東西是如何關聯到一起的呢?它們如何被android的framework層所識別呢?
3.組件的源碼
我們看下TextView的源碼:
Java代碼
public TextView(Context context) {
this(context, null);
}//這個構造器用來給用戶調用,比如new TextView(this);
public TextView(Context context,
AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.textViewStyle);
}
public TextView(Context context,
AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);//為用戶自定義的TextView設置默認的style
mText = "";
//設置畫筆
mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.density = getResources().getDisplayMetrics().density;
mTextPaint.setCompatibilityScaling(
getResources().getCompatibilityInfo().applicationScale);
mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHighlightPaint.setCompatibilityScaling(
getResources().getCompatibilityInfo().applicationScale);
mMovement = getDefaultMovementMethod();
mTransformation = null;
//attrs中包含了這個TextView控制項在布局文件中定義的屬性,比如android:background,android:layout_width等
//com.android.internal.R.styleable.TextView中包含了TextView中的針對attrs中的屬性的默認的值
//也就是說這個地方能夠將布局文件中設置的屬性獲取出來,保存到一個TypeArray中,為這個控制項初始化各個屬性
TypedArray a =
context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TextView, defStyle, 0);
int textColorHighlight = 0;
ColorStateList textColor = null;
ColorStateList textColorHint = null;
ColorStateList textColorLink = null;
int textSize = 15;
int typefaceIndex = -1;
int styleIndex = -1;
/*
* Look the appearance up without checking first if it exists because
* almost every TextView has one and it greatly simplifies the logic
* to be able to parse the appearance first and then let specific tags
* for this View override it.
*/
TypedArray appearance = null;
//TextView_textAppearance不太了解為什麼要這樣做?難道是為了設置TextView的一些默認的屬性?
int ap = a.getResourceId(com.android.internal.R.styleable.TextView_textAppearance, -1);
if (ap != -1) {
appearance = context.obtainStyledAttributes(ap,
com.android.internal.R.styleable.
TextAppearance);
}
if (appearance != null) {
int n = appearance.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = appearance.getIndex(i);
switch (attr) {
case com.android.internal.R.styleable.TextAppearance_textColorHighlight:
textColorHighlight = appearance.getColor(attr, textColorHighlight);
break;
case com.android.internal.R.styleable.TextAppearance_textColor:
textColor = appearance.getColorStateList(attr);
break;
case com.android.internal.R.styleable.TextAppearance_textColorHint:
textColorHint = appearance.getColorStateList(attr);
break;
case com.android.internal.R.styleable.TextAppearance_textColorLink:
textColorLink = appearance.getColorStateList(attr);
break;
case com.android.internal.R.styleable.TextAppearance_textSize:
textSize = appearance.getDimensionPixelSize(attr, textSize);
break;
case com.android.internal.R.styleable.TextAppearance_typeface:
typefaceIndex = appearance.getInt(attr, -1);
break;
case com.android.internal.R.styleable.TextAppearance_textStyle:
styleIndex = appearance.getInt(attr, -1);
break;
}
}
appearance.recycle();
}
//各類屬性
boolean editable = getDefaultEditable();
CharSequence inputMethod = null;
int numeric = 0;
CharSequence digits = null;
boolean phone = false;
boolean autotext = false;
int autocap = -1;
int buffertype = 0;
boolean selectallonfocus = false;
Drawable drawableLeft = null, drawableTop = null, drawableRight = null,
drawableBottom = null;
int drawablePadding = 0;
int ellipsize = -1;
boolean singleLine = false;
int maxlength = -1;
CharSequence text = "";
CharSequence hint = null;
int shadowcolor = 0;
float dx = 0, dy = 0, r = 0;
boolean password = false;
int inputType = EditorInfo.TYPE_NULL;
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
//通過switch語句將用戶設置的,以及默認的屬性讀取出來並初始化
switch (attr) {
case com.android.internal.R.styleable.TextView_editable:
editable = a.getBoolean(attr, editable);
break;
case com.android.internal.R.styleable.TextView_inputMethod:
inputMethod = a.getText(attr);
break;
case com.android.internal.R.styleable.TextView_numeric:
numeric = a.getInt(attr, numeric);
break;
//更多的case語句...
case com.android.internal.R.styleable.TextView_textSize:
textSize = a.getDimensionPixelSize(attr, textSize);//設置當前用戶所設置的字體大小
break;
case com.android.internal.R.styleable.TextView_typeface:
typefaceIndex = a.getInt(attr, typefaceIndex);
break;
//更多的case語句...
}
通過上面的代碼大概可以知道,每個組件基本都有3個構造器,其中只傳遞一個Context上下文的那個構造器一般用來在java代碼中實例化使用。
比如你可以
Java代碼
TextView tv = new TextView(context);
來實例化一個組件。
最終調用的是第3個構造器
Java代碼
public TextView(Context context,
AttributeSet attrs,
int defStyle)
在這個構造器中為你設置了默認的屬性attrs和值styles。關鍵不在這里,而是後面通過使用下面的代碼
Java代碼
TypedArray a =
context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TextView, defStyle, 0);
來將屬性和值獲取出來,放到一個TypeArray中,然後再利用一個switch語句將裡面的值取出來。再利用這些值來初始化各個屬性。這個View最終利用這些屬性將這個控制項繪制出來。
如果你在布局文件中定義的一個View的話,那麼你定義的值,會被傳遞給構造器中的attrs和styles。也是利用同樣的方式來獲取出你定義的值,並根據你定義的值來繪制你想要的控制項。
再比如其實Button和EditText都是繼承自TextView。看上去兩個控制項似乎差異很大,其實不然。Button的源碼其實相比TextView變化的只是style而已: