您的位置:首页 > 其它

ToggleButton

2015-08-11 21:31 274 查看
ToggleButton有两种状态:

1>选中(true)

2>未选中(false)

ToggleButton属性:

android:checked=”true”——-表示默认选中,false表示默认不被选中

android:textOn=”开”

android:textOff=”关”

通过ToggleButton与ImageView来实现点击按钮切换图片功能!

activity_main.xml代码如下;

[code]<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"
    tools:context="${relativePackage}.${activityClass}" >

    <ToggleButton
        android:id="@+id/togglebutton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textOn="开"
        android:textOff="关"
        android:checked="true"
        />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/togglebutton1"
        android:background="@drawable/on" />

</RelativeLayout>


MainActivity.java中的代码如下:

[code]package com.example.togglebutton;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements OnCheckedChangeListener{
    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.imageView1);

        tb.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
        img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
    }
}


可以实现点击按钮进行图片切换!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: