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>
这种自带机制很实用,此例结束。
时间: 2024-10-01 21:39:34