Button 有按下效果 - 续
上次讲过 如何使得Button有按下的效果 但是最后也提过 如果要求几个Button都有这种效果 分别为每一个Button定义一个 *.xml 是不方便的 今天就演示一下简便一点的做法
?
?
[代码 步骤]
1. 准备这2个ImageButton 所需的 *.ico 如:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" ><ImageButton android:id="@+id/play" android:layout_width="wrap_content" android:layout_height="wrap_content" /><ImageButton android:id="@+id/pause" android:layout_width="wrap_content" android:layout_height="wrap_content" /></LinearLayout>?
?
?
3. 分别为View 定义名称 便于引用
public void initialView(){ play = (ImageButton) findViewById(R.id.play); pause = (ImageButton) findViewById(R.id.pause); }?
?
4. 为ImageButton play,pause 指定默认背景
public void specifyBackground(){ play.setBackgroundResource(R.drawable.play); pause.setBackgroundResource(R.drawable.pause); }?
?
5. 为ImageButton play,pause 注册 onTouch() 事件 并根据其ID 与 状态 指定具体的背景图
@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubswitch(v.getId()){case R.id.play:if(event.getAction() == MotionEvent.ACTION_DOWN){v.setBackgroundResource(R.drawable.play_down);}else if(event.getAction() == MotionEvent.ACTION_UP){v.setBackgroundResource(R.drawable.play);}break;case R.id.pause:if(event.getAction() == MotionEvent.ACTION_DOWN){v.setBackgroundResource(R.drawable.pause_down);}else if(event.getAction() == MotionEvent.ACTION_UP){v.setBackgroundResource(R.drawable.pause);}break;}return false;} }; play.setOnTouchListener(listener); pause.setOnTouchListener(listener);?
?
?
6. 所有程序为:
public class ButtonStyle3Usage extends Activity {ImageButton play,pause;OnTouchListener listener;/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initialView(); specifyBackground(); listener = new OnTouchListener(){@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubswitch(v.getId()){case R.id.play:if(event.getAction() == MotionEvent.ACTION_DOWN){v.setBackgroundResource(R.drawable.play_down);}else if(event.getAction() == MotionEvent.ACTION_UP){v.setBackgroundResource(R.drawable.play);}break;case R.id.pause:if(event.getAction() == MotionEvent.ACTION_DOWN){v.setBackgroundResource(R.drawable.pause_down);}else if(event.getAction() == MotionEvent.ACTION_UP){v.setBackgroundResource(R.drawable.pause);}break;}return false;} }; play.setOnTouchListener(listener); pause.setOnTouchListener(listener); } public void initialView(){ play = (ImageButton) findViewById(R.id.play); pause = (ImageButton) findViewById(R.id.pause); } public void specifyBackground(){ play.setBackgroundResource(R.drawable.play); pause.setBackgroundResource(R.drawable.pause); }}?
?
7. emulator 运行截图: 静态
?