selector
1.selector 從單詞的意思來說:選擇者,選擇器,就是對你的目標的控制。
從API來說:
A controller for the selection of SelectableChannel objects. Selectable channels can be registered with a selector and get a SelectionKey that represents the registration. The keys are also added to the selector's key set. Selection keys can be canceled so that the corresponding channel is no longer registered with the selector.
By invoking the select method, the key set is checked and all keys that have been canceled since last select operation are moved to the set of canceled keys. During the select operation, the channels registered with this selector are checked to see whether they are ready for operation according to their interest set
其實API 說了那么就是在解釋單詞的意思。
selector主要是用在ListView的item單擊樣式和TextView和Button的點擊樣式。
2.現在對他的一些屬性進行介紹
屬性介紹:
android:state_selected選中
android:state_focused獲得焦點
android:state_pressed點擊
android:state_enabled設置是否響應事件,指所有事件
3.下面通過例子來說一下selector對TextView和ListView的設置:
TextView:
1).在res下創建一個drawable文件夾用於裝textselector.xml ,對點擊樣式的定義放在這里面
2).values下定義colors.xml文件,將顏色資源放在里面
3).將textselector.xml資源加載到TextView上,
textselector.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <selector xmlns:android="http://schemas.android.com/apk/res/android"> 3 <item android:state_pressed="true" android:color="@color/red"></item> <!-- 點擊后的字體顏色 --> 4 <item android:color="@color/gray"></item> <!-- 默認字體顏色 --> 5 </selector>
activity.xml
1 <TextView 2 android:id="@+id/text" 3 android:layout_width="wrap_content" 4 android:layout_height="wrap_content" 5 android:text="@string/hello_world" 6 android:textColor="@drawable/textselector" 7 android:textSize="15dp" 8 /> <!-- textColor對 selector引用 -->
這樣運行程序去點擊textview是不會看到textview顏色改變的,這是因為還沒有給TextView添加按鈕監聽事件,就算事件不取執行什么功能都必須去設置。
1 TextView text = (TextView)findViewById(R.id.text); 2 text.setOnClickListener(null);
終上所述:就有效果了
下面會說說ListView:
(1)在ListView中添加如下屬性代碼
- android:listSelector="@drawable/mylist_view"
<android:listSelector="@drawable/mylist_view" />
(2)在ListView的item界面中添加如下屬性代碼
1 <android:background="@drawable/mylist_view" />
(3)利用JAVA代碼直接編寫
1 Drawable drawable = getResources().getDrawable(R.drawable.mylist_view); 2 3 listView.setSelector(drawable);
