码迷,mamicode.com
首页 > 移动开发 > 详细

安卓天天练练(五)CompoundButton

时间:2015-07-23 19:36:59      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

toggleButton 让我想起了从前jQuery还没有取消toggle方法的时候偷的懒。。

package com.example.android_8_1;

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 {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ToggleButton tg = (ToggleButton) findViewById(R.id.toggleButton1);
        tg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            // imported from android.widget.CompoundButton
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                setBulbState(isChecked);
            }
        });
    }

    public void setBulbState(boolean state) {
        ImageView iv = (ImageView) findViewById(R.id.imageView1);
        iv.setImageResource((state) ? R.drawable.btn : R.drawable.btnhover);

        ToggleButton tg = (ToggleButton) findViewById(R.id.toggleButton1);
        tg.setChecked(state);
    }

}

XML很简单

<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.android_8_1.MainActivity" >

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="61dp"
        android:text="ToggleButton"
        android:textOff="Off"
        android:textOn="On"
         />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:src="@drawable/btn" />

</RelativeLayout>

这种自带机制很实用,此例结束。

安卓天天练练(五)CompoundButton

标签:

原文地址:http://www.cnblogs.com/haimingpro/p/4671239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!