首先、准备好资源、得有两张图片
1、将两张图片内放入drawable-hdpi文件夹下;
2、在res/drawable文件夹下创建my_transition.xml文件
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/lamp_off"></item>
<item android:drawable="@drawable/lamp_on"></item>
</transition>
3、在main_activity.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"
>
<ImageView
android:id="@+id/main_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/my_transition" />
<Switch
android:id="@+id/main_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/main_iv"
android:layout_centerHorizontal="true"
android:layout_marginTop="47dp"
android:textOff="关"
android:textOn="开" />
</RelativeLayout>
4、在MainActivity.java中编写:
public class MainActivity extends Activity {
private ImageView iv;
private Switch sw;
private TransitionDrawable td;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv=(ImageView) findViewById(R.id.main_iv);
sw=(Switch) findViewById(R.id.main_switch);
td=(TransitionDrawable) iv.getDrawable();
sw.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
td.startTransition(500);
}else{
td.reverseTransition(5000);
}
}
});
}
}
5、运行就ok了,在下简单学习后,挺有意思的,大家可以互相学习。