用ToggleButton和ImageView实现不同状态下显示的切换
靠,写的时候第一次因为把implements OnCheckedChangeListener这里实现的接口写错了,搞了很久,
后来发现又少了这两句错了
btn = (ToggleButton) findViewById(R.id.toggleButton1);
view = (ImageView) findViewById(R.id.imageView1);
后来又发现把这里private ImageView view;的Imageview写成ImageButton了
够了够了,细心细心
1:空间设置代码:
<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=".MainActivity" > <ToggleButton android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="ToggleButton" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/toggleButton1" android:layout_marginTop="102dp" android:background="@drawable/off" /> </RelativeLayout>
2:主文件
package com.g.Deng; import android.media.ToneGenerator; import android.os.Bundle; import android.app.Activity; import android.view.Menu; 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 btn; private ImageView view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //一定不要忘记这里,给两个空间附初值 btn = (ToggleButton) findViewById(R.id.toggleButton1); view = (ImageView) findViewById(R.id.imageView1); /** * 设置监听器 */ btn.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) { // TODO Auto-generated method stub //用arg1监听空间的状态,如果为真就打开,如果为假就关闭 view.setBackgroundResource(arg1?R.drawable.on:R.drawable.off); } }