ToggleButton开关按钮
xml文件如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="你今天开心吗?"
/>
<!--
ToggleButton开关控件
textOff:关闭的时候显示的文字
textOn:开启的时候显示的文字
checked:为true则默认打开,false则默认关闭
-->
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="不开心"
android:textOn="开心"
/>
</LinearLayout>
xml文件效果
Java代码如下
package com.example.ui_togglebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity
{
private ToggleButton toggleButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.linearlayout);
toggleButton=(ToggleButton)findViewById(R.id.toggleButton);
//匿名内部类实现监听器
toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0)
{
//参数arg0是被点击的ToggleButton控件
if(toggleButton.isChecked())//如果ToggleButton被打开。注意这里没有用arg0,若要用arg0则要强制转换为ToggleButton类型才能使用isChecked()方法
{
Toast.makeText(MainActivity.this, "好开心呀好开心", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(MainActivity.this, "不开心QAQ", Toast.LENGTH_SHORT).show();
}
});
}
}