1. 程式人生 > >學習筆記-----listview中含有togglebutton

學習筆記-----listview中含有togglebutton

還是小菜鳥一直,今天開始嘗試寫部落格,其實就是自己的學習筆記吧
今天要寫的是一個listview中含有togglebutton的一些自己所需要注意的地方。
其餘的就不說,就直接標題,緣由是要寫一個隱私設定,需要一個開關,之前用preference來寫,但是自己還是小菜鳥,preference用不好,所以又換成普通activity來寫,在preference時候的xml是有一個switchPreference的,有他的title,summay等,很標準的,但是有個問題,版本不同他的樣式是不同的,要求樣式一致就要自己設開關的樣式,我就用的togglebutton 來弄
太多廢話了。。

因為這個togglebutton如果用系統自己的,會因為版本不同樣式會不一樣,所以先找好自己的toggle樣式圖片,我用的是
這裡寫圖片描述


以及
這裡寫圖片描述

分別是開和關的樣式,大概樣子就是這樣

然後把他們分別匹配到togglebutton上

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
        android:drawable="@drawable/bitmap_privacy_switch_on" /> <!-- pressed -->
<item android:state_checked="false" android:drawable="@drawable/bitmap_privacy_switch_off"/> <!-- default/unchecked --> </selector>

我要做的是在listview裡的toggle,所以做好toggle所在的item佈局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="50dp" android:clickable="true" android:descendantFocusability="blocksDescendants" >
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#5C5C5C" android:paddingTop="20dp" android:paddingLeft="15dp" android:id="@+id/title_tv" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="15dp" android:textColor="#C8C8C8" android:id="@+id/describe_tv" /> </LinearLayout> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="22dp" android:layout_alignParentRight="true" > <ToggleButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="" android:textOff="" android:background="@drawable/toggle_privacy_set" android:layout_alignParentRight="true" android:id="@+id/privacy_set_tb" android:focusable="false" android:clickable="true" /> </RelativeLayout> </RelativeLayout>

程式碼習慣什麼的小細節就不要在意了,

要注意的幾點是
1,因為所用的togglebutton用我們之前寫好的兩個bitmap來作為我們想要的樣式,用的是background,但是如果直接這樣的話,會導致你的圖片被拉伸成系統本來的togglebutton大小輪廓,超級難看,所以為了不讓它拉伸,需要再加個

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/privacy_switch_on_bm"
    android:src="@mipmap/ic_switch_on"
    android:tileMode="disabled" android:gravity="top">
</bitmap>  

這樣圖片作為background時就不會被拉伸,當然兩張圖都要這樣弄
在將這兩張圖設定成togglebutton的開關樣式,就是剛開始所提到的

2,
item的xml問價中根目錄的

android:clickable="true"
android:descendantFocusability="blocksDescendants"

以及togglebutton中

android:focusable="false"
android:clickable="true"

這幾句是為了不讓item和togglebutton點選事件衝突,這四句加上是最保險的,讓item和togglebutton各自的點選事件都響應

差不多就是這樣了

繼續加油!