Button 有按下效果
[功能]
讓Button 有按下效果 更有視覺效果
[代碼]
1. 先準備2張*.png 一張供預設使用 另一張供按下使用 本例為:
Java代碼
play.png
play_down.png
play.pngplay_down.png
2. 根據各種狀態 定製化所顯示的 *.png 命名為: myselection.xml
Java代碼
<item
android:state_pressed="false"
android:drawable="@drawable/play" />
<item
android:state_pressed="true"
android:drawable="@drawable/play_down" />
<item
android:drawable="@drawable/play" />
3. 在 main.xml 布局中 添加Button 元件 並 設定 使用 myselection.xml
Java代碼
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<textview
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button Style!"
/>
<imagebutton
android:id="@+id/playorpause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@xml/myselection"
android:background="#00000000" />
4. 大家可以自己看看效果 因為不好
其實 除了上面的方法 還有一個方法 為:
1. 在 maun.xml 中添加 ImageButton 且不設定使用的*.png
Java代碼
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<imagebutton
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
2. 在該ImageButton上設定監聽器 並根據其狀態使用對應的資源 但是必須要設定預設資源
Java代碼
ImageButton btn = (ImageButton) findViewById(R.id.button);
//to set its default *.png
btn.setBackgroundResource(R.drawable.play);
btn.setOnTouchListener(new ImageButton.OnTouchListener(){
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
if(arg1.getAction() == MotionEvent.ACTION_DOWN){
arg0.setBackgroundResource(R.drawable.play_down);
}
else if(arg1.getAction() == MotionEvent.ACTION_UP){
arg0.setBackgroundResource(R.drawable.play);
}
return false;
}
});
ImageButton btn = (ImageButton) findViewById(R.id.button); //to set its default *.png btn.setBackgroundResource(R.drawable.play); btn.setOnTouchListener(new ImageButton.OnTouchListener(){ @Override public boolean onTouch(View arg0, MotionEvent arg1) { // TODO
Auto-generated method stub if(arg1.getAction() == MotionEvent.ACTION_DOWN){ arg0.setBackgroundResource(R.drawable.play_down); } else if(arg1.getAction() == MotionEvent.ACTION_UP){ arg0.setBackgroundResource(R.drawable.play); } return false; } });
具體哪個方法更好 應該根據自己的場合:
1. 只有一個Button 推薦使用第一個方法
2. 有幾個Button 推薦使用第二個 統一定義 然後根據指定的id 來使用目標*.png