布局文件
<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"
>
<!--ToggleButton 开关 4.0之前使用 -->
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="开"
android:textOff="关"
android:checked="true"
android:onClick="onToggleButton"
/>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/bg1"
android:layout_centerInParent="true"
/>
</RelativeLayout>
Java代码
package com.qianfeng.day03_tagglebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
private ImageView iv ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
}
public void onToggleButton(View v){
ToggleButton tb = (ToggleButton) v;
boolean isChecked = tb.isChecked();
if(isChecked){
iv.setImageResource(R.drawable.bg1);
}else{
iv.setImageResource(R.drawable.bg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}