您的位置:首页 > 移动开发 > Android开发

Android ToggleButton(开关)

2017-06-06 20:41 225 查看
效果图:





代码:

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">

<!--checked:是否处于开启状态-->
<!--textOff:关闭状态显示的文字-->
<!--textOn:开启状态显示的文字-->
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:id="@+id/tb_main_but"
android:textOff="开"
android:textOn="关"
/>

</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.Toast;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

private ToggleButton tb_main_but;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//根据id获得ToggleButton的控件
tb_main_but = (ToggleButton) findViewById(R.id.tb_main_but);
//给ToggleButton设置监听事件
tb_main_but.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();
}
}
});
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: