在res/layout中创建myselector.xml,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="false"
android:drawable="@drawable/play"/>
<item
android:state_pressed="true"
android:drawable="@drawable/stop"/>
</selector>
在res/layout中创建main.xml,代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:id="@+id/btn" />
</LinearLayout>
MainActivity.java代码如下:
package com.example.playbutton;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class MainActivity extends ActionBarActivity {
static boolean isPlay = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//按钮初始默认是"播放"
ImageButton button1 = (ImageButton)findViewById(R.id.btn);
button1.setImageResource(R.drawable.play);
//监听"播放/暂停"按钮
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(isPlay){
((ImageButton)v).setImageResource(R.drawable.stop);
}
else{
((ImageButton)v).setImageResource(R.drawable.play);
}
isPlay = !isPlay;
}
});
}
}