android studio开发笔记三

1.ToggleButton:有两种状态:选中和未被选中状态,并且需要为不同的状态设置不同的显示文本
2.ToggleButton属性:android:checked="true" android:textOff="关" android:textOn="开"
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.demo2.MainActivity">

<ToggleButton
android:id="@+id/toggleButton1"
android:checked="false"
android:textOff="关闭"
android:textOn="打开"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/image1"
android:background="@drawable/off"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

MainActivity:
package com.example.administrator.demo2;

import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity{
private ToggleButton tb;
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
tb=(ToggleButton)findViewById(R.id.toggleButton1);
img=(ImageView)findViewById(R.id.image1);
//给当前的tb设置监听器
tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
/*
当tb被点击时,当前方法会被执行
buttonView代表被点击控件的本身
ischecked代表被点击控件的状态
当点击tb时,更换img的背景
*/
img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
}
});
}
}

posted @ 2016-09-03 12:07  xiaofeiyang  阅读(425)  评论(0编辑  收藏  举报