效果图:
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-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.example.blogtest.MainActivity">
<!--textOff:关闭状态显示的文字-->
<!--textOn:开启状态显示的文字-->
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/sc_main_swi"
android:textOn="关"
android:textOff="开"
/>
</LinearLayout>
Java代码:
package com.example.blogtest;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.CompoundButton;
import android.widget.RatingBar;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private Switch sw_main_swi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//根据id获得Switch的控件
sw_main_swi = (Switch) findViewById(R.id.sc_main_swi);
//给ToggleButton设置监听事件
sw_main_swi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Toast t= Toast.makeText(MainActivity.this,"开启状态",Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER,0,0);
t.show();
}else{
Toast t= Toast.makeText(MainActivity.this,"关闭状态",Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER,0,0);
t.show();
}
}
});
}
}