From
Developer.android.com: “A Switch is a two-state toggle switch widget that can
select between two options. The user may drag the "thumb" back and
forth to choose the selected option, or simply tap to toggle as if it were a
checkbox. The text property controls the text displayed in the label for the
switch, whereas the off and on text controls the text on the thumb…”
In this tutorial, we show you how to customize a Switch, add a
click listener and get the setOnCheckedChangeListener
for this Switch. Use Switch to control with media volume and wifi on device.
Here is a result of this tutorial:
Here is a result of this tutorial:
This project is developed in Eclipse 4.2.0.
1.
First, modify the main layout of app. Open “res/layout/main.xml” file, add two switches,
few textviews and a button.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Disable all
switch"
android:layout_marginBottom="15dp"
android:onClick="button_click"/>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/switch1"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp"
android:text="Media Volume"/>
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="OFF"
android:textOn="ON"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:onClick="onSwitchClicked"
android:thumb="@drawable/switch_bg"
android:track="@drawable/track_bg"
android:layout_marginBottom="15dp"
/>
<TextView android:layout_below="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/switch2"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp"
android:text="Wifi"/>
<Switch android:layout_below="@+id/switch1"
android:id="@+id/switch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="OFF"
android:textOn="ON"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:onClick="onSwitchClicked"
android:thumb="@drawable/switch_bg"
android:track="@drawable/track_bg"
android:layout_marginBottom="15dp"
/>
</RelativeLayout>
<TextView android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="27px"
android:layout_marginTop="15dp"
android:text="Show spinner choice"
android:gravity="center"
android:textColor="#CD2134"
android:textStyle="bold" />
</LinearLayout>
Note two attribute of Switch below:
android:thumb="@drawable/switch_bg"
android:track="@drawable/track_bg"
We need two xml files “switch_bg.xml” and “track_bg.xml” in
folder drawable to customize for all switches:
res/drawable/switch_bg:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/enable"
/>
<item android:state_pressed="true" android:drawable="@drawable/press"
/>
<item android:state_checked="true" android:drawable="@drawable/check_on"
/>
<item android:drawable="@drawable/enable" />
</selector>
res/drawable/track_bg:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/track_disable"
/>
<item android:drawable="@drawable/track_default" />
</selector>
2. CODE.
2.1.
Add click listener to all Switches
Use android:onClick attribute in the Switch XML
definition:
android:onClick="onSwitchClicked "
Within the activity that hosts this layout, the following
method handles the click event for all switches, one switch for ON/OFF Media
Volume, and one for ON/OFF Wifi on device.
public void onSwitchClicked(View view) {
switch(view.getId()){
case R.id.switch1:
if(switch1.isChecked()) {
textview.setText("Switch 1 check ON by click on it");
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
8, 0);
}
else {
textview.setText("Switch 1 check OFF by click on it");
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
0, 0);
}
break;
case R.id.switch2:
if(switch2.isChecked()) {
textview.setText("Switch 2 check ON by click on it");
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
else {
textview.setText("Switch 2 check OFF by click on it");
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}
break;
}
}
2.2. How to get the setOnCheckedChangeListener for Switch. This method is
executed when the User drag the thumb or click on the Switch, and then do
similar with onClick method of this Switch
switch1.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()){
textview.setText("Switch 1 check ON by drag thumb");
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 8, 0); }
else{
textview.setText("Switch 1 check OFF by drag thumb");
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
}
}
});
switch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()){
textview.setText("Switch 2 check ON by drag thumb");
wifiManager = (WifiManager)
getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
else{
textview.setText("Switch 2 check OFF by drag thumb");
wifiManager = (WifiManager)
getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}
}
});
2.3. Finally, add
button onClick method to enable or disable all Switches
public void button_click(View view){
if(is_enable == true)
{
is_enable = false;
button.setText("Enable all switch");
textview.setText("Switch is Disable by click on button");
}
else{
is_enable = true;
button.setText("Disable all switch");
textview.setText("Switch is Enable by click on button");
}
switch1.setEnabled(is_enable);
switch2.setEnabled(is_enable);
}
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
3. DEMO
3.1. Run Application
3.2. When click on
Switch 1 to ON/OFF Media Volume of device
3.3. When drag thumb
on Switch 2 to ON/OF Wifi
4.4. Click on button
to Enable or Disable all Switches
You can download all source codes of this
tutorial from here
Reference:
http://developer.android.com/reference/android/widget/Switch.html
This comment has been removed by the author.
ReplyDeleteHi, great post! Thanks. I can't get any of the styles to change. I've tried track, thumb, textOn, textOff and nothing changes. Can you think of anything I may be doing wrong? Thanks again.
ReplyDeleteHello,
ReplyDeleteI'm wondering if for your drawables such as drawable/enabled you're using your own defined xml files, or if you're using an image of some sort. If you are using an xml file is there any chance I could get a look at a sample version of it?
Thanks,
Hello,
ReplyDeleteSame here,
Wanted to know what your xml files were for the drawables for the switch_bng and the track_bng.
Cheers
Where is the whole code?
ReplyDeleteThis isn't complete, it is missing so much.. Bad tutorial.
ReplyDeleteWhat a great online source of information about this topic. You have done great work....Well done!!
ReplyDeleteIf you want to make custom website & application you can contact us on our Android Application Development Company and Mobile Application Development Company anytime.
Nice & Informative Blog !
ReplyDeleteQuickBooks is an easy-to-use accounting software that helps you manage all the operations of businesses. In case you want immediate help for QuickBooks issues, call us on QuickBooks Technical Support Phone Number 1-855-974-6537.
Thanks for sharing wonderful articl, This is excellent valuable & informative post.Keep on posting like this... App Development Company in Texas
ReplyDeletecontent with coding explanation is awesome. great to read and getting information.
ReplyDeleteit will be very useful for developers.
.web development company in coimbatore
Mobile App developers in coimbatore
instagram takipçi satın al
ReplyDeletecasino siteleri
WB74A
bayrampaşa
ReplyDeletegüngören
hakkari
izmit
kumluca
ZR78
Malatya
ReplyDeleteKırıkkale
Aksaray
Bitlis
Manisa
MHNO4
görüntülüshow
ReplyDeleteücretli show
0UX
https://titandijital.com.tr/
ReplyDeleteafyon parça eşya taşıma
düzce parça eşya taşıma
erzincan parça eşya taşıma
elazığ parça eşya taşıma
7M74U
شركة مكافحة
ReplyDeleteشركة مكافحة حشرات
AF8F1
ReplyDeleteDiyarbakır Lojistik
Adıyaman Şehir İçi Nakliyat
Karaman Lojistik
Bitfinex Güvenilir mi
Etimesgut Parke Ustası
Çankaya Parke Ustası
Burdur Şehir İçi Nakliyat
Çerkezköy Oto Lastik
Bilecik Lojistik
14C38
ReplyDeletereferans kodu %20
9CBB0
ReplyDeleteçankırı parasız görüntülü sohbet uygulamaları
siirt canli sohbet bedava
edirne en iyi sesli sohbet uygulamaları
van yabancı sohbet
aksaray bedava sohbet chat odaları
trabzon canlı sohbet siteleri
bartın mobil sohbet
muğla bedava sohbet siteleri
konya sohbet muhabbet
203DF
ReplyDeleteistanbul sesli sohbet uygulamaları
Kırıkkale Görüntülü Sohbet Ücretsiz
Ağrı Mobil Sesli Sohbet
elazığ goruntulu sohbet
sesli sohbet odası
goruntulu sohbet
afyon sesli sohbet uygulamaları
ankara canlı görüntülü sohbet
trabzon kadınlarla rastgele sohbet
7EF34
ReplyDeleteLinkedin Takipçi Hilesi
Floki Coin Hangi Borsada
Btcst Coin Hangi Borsada
Star Atlas Coin Hangi Borsada
Bitcoin Kazanma
Bitcoin Kazanma Siteleri
Yeni Çıkan Coin Nasıl Alınır
Pinterest Takipçi Hilesi
Bitcoin Kazanma
4BB55
ReplyDeleteCoin Kazanma Siteleri
Referans Kimliği Nedir
Bitcoin Nasıl Kazılır
Star Atlas Coin Hangi Borsada
Referans Kimliği Nedir
Madencilik Nedir
Kaspa Coin Hangi Borsada
Hexa Coin Hangi Borsada
Görüntülü Sohbet Parasız
tghgfjnhgjmhkmjhk
ReplyDeleteتصليح افران الاحساء
HYGNJHJKUK
ReplyDeleteمكافحة النمل الابيض
شركة عزل اسطح بالرياض uKp6BXdQ0q
ReplyDeleteشركة تسليك مجاري بالاحساء FPceKMaB6u
ReplyDeleteشركة تنظيف افران بعنيزة wndUCu4Eje
ReplyDeleteشركة مكافحة حشرات بالهفوف sjEY5JiLzv
ReplyDeleteشركة تنظيف مكيفات بالاحساء lVjscJkjJG
ReplyDeleteشركة رش مبيدات بالاحساء 1hVAuZ6iou
ReplyDeleteشركة تنظيف موكيت بالاحساء gmhlEAnNgs
ReplyDeleteشركة عزل اسطح بالجوف RpjKRKcVcA
ReplyDeleteشركة عزل مواسير المياه بالاحساء 448xxv6MwQ
ReplyDeleteشركة صيانة خزانات بعنيزة WXxzh5NYZw
ReplyDeleteشركة عزل اسطح بابها u5GNfQMFqO
ReplyDelete