[Android] 為ImageButton添加按下的動畫效果 變亮或變暗

來源:互聯網
上載者:User

Android中使用ImageButton的話,程式裡按下那個ImageButton時感覺不到任何按下的效果。

網上有2中經典的解決方案,一種是使用xml,一種是寫在代碼裡。

 

這裡我想要介紹另一種方法,使ImageButton有按下的特效,只需要準備一張普通的圖片,不需要按下效果的圖片。

直接看範例程式碼,建立 TouchLight 和 TouchDark 這兩個 OnTouchListener,然後給 ImageButton 設定OnTouchListener就行了,如果使用TouchLight,則按下效果是按鍵變亮;另一個就是變暗。

 

import android.app.Activity;import android.graphics.ColorMatrixColorFilter;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;public class TouchedAnimation extends Activity {public static final OnTouchListener TouchLight = new OnTouchListener() {public final float[] BT_SELECTED = new float[] {1,0,0,0,50,0,1,0,0,50,0,0,1,0,50,0,0,0,1,0};public final float[] BT_NOT_SELECTED = new float[] {1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0};@Overridepublic boolean onTouch(View v, MotionEvent event) {if (event.getAction() == MotionEvent.ACTION_DOWN) {v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_SELECTED));v.setBackgroundDrawable(v.getBackground());} else if (event.getAction() == MotionEvent.ACTION_UP) {v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));v.setBackgroundDrawable(v.getBackground());}return false;}};public static final OnTouchListener TouchDark = new OnTouchListener() {public final float[] BT_SELECTED = new float[] {1,0,0,0,-50,0,1,0,0,-50,0,0,1,0,-50,0,0,0,1,0};public final float[] BT_NOT_SELECTED = new float[] {1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0};@Overridepublic boolean onTouch(View v, MotionEvent event) {if (event.getAction() == MotionEvent.ACTION_DOWN) {v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_SELECTED));v.setBackgroundDrawable(v.getBackground());} else if (event.getAction() == MotionEvent.ACTION_UP) {v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));v.setBackgroundDrawable(v.getBackground());}return false;}};        @Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);ImageButton ib1, ib2;                ib1 = (ImageButton) findViewById(R.id.ImageButton01);                ib2 = (ImageButton) findViewById(R.id.ImageButton02);                ib1.setOnTouchListener(TouchLight);                ib2.setOnTouchListener(TouchDark);}}

代碼裡的兩個 float 數組裡存的東西是顏色矩陣,不瞭解顏色矩陣也沒關係,使用這個附件就行,只需調整亮度、對比之類的值,然後把生產的顏色矩陣複製到代碼裡。

附件:ColorMatrixDemo.swf

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.