TextView這個控件我們已經很熟悉了,但是CheckedTextView這個控件呢?CheckedTextView在新手教程上是沒有的,當Android入門之後再接觸這個控件更爲合適。
上圖可以看出,CheckedTextView
本質上是一個TextView,比TextView多實現了Checkable
接口,Checkable
接口源碼如下:
/**
* Defines an extension for views that make them checkable.
*
*/
public interface Checkable {
/**
* Change the checked state of the view
*
* @param checked The new checked state
*/
void setChecked(boolean checked);
/**
* @return The current checked state of the view
*/
boolean isChecked();
/**
* Change the checked state of the view to the inverse of its current state
*
*/
void toggle();
}
Checkable作爲CheckedTextView的一個擴展,爲CheckedTextView添加一個選中屬性。
Checkable的三個方法的意思很容易理解,和字面上的意思一樣:
- setChecked:設置CheckedTextView的選中狀態
- isChecked:CheckedTextView是否選中
- toggle:切換選中狀態
我們都知道,具有選中狀態的組件有:CheckBox、RadioButton、、RadioGroup,那麼CheckedTextView
明顯也具有選中狀態,那麼它的選中狀態具體表現在什麼地方呢?
如上圖所示,文本後面有個複選框,然而,我並沒有在文本後面添加複選框組件,佈局代碼如下:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="100dp">
<CheckedTextView
android:id="@+id/checkedTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="26sp"
android:padding="10dp"
android:gravity="center"
android:checked="true"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:text="嫦娥" />
</LinearLayout>
文本後面之所以出現複選框,是因爲checkMark
屬性,添加這個屬性可以讓文本後面新增一個複選框,這個用法也就是CheckedTextView的精華所在了。
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
當然,默認情況下,點擊是沒有效果的,還必須給CheckedTextView添加點擊事件
checkedTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkedTextView.toggle();
}
});
每次點擊時都會切換
選中狀態。
CheckedTextView的好處在於:使代碼更加簡單
。
目前複選框的顏色是主題色,那麼怎麼修改複選框的顏色呢?我想這篇文章會找到答案。普通CheckBox使用
CheckedTextView還有其他屬性,checkMarkTint
和checkMarkTintMode
,這兩個屬性往往一起使用,和右側圖像相組合,合成一個新的圖像。但是,不知道爲什麼,這兩個屬性設置無效了。
另外,如下圖:
ListView有setChoiceMode
方法,往往和CheckedTextView
的
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
屬性配合使用,由於想在ListView控件基本不用了,所以本章就此省略。(現在都用RecyclerView了)
[本章完...]