2013-07-30 41 views
3

我有很多不同的背景顏色的按鈕。我想知道是否有辦法在點擊時應用一些顏色過濾器。例如,我希望所有按鈕在點擊時變暗。他們保持原來的顏色,但它更黑。在按鈕上應用顏色過濾器

是否有一個簡單的方法來做到這一點,或者我必須爲每個按鈕定義較深的顏色?

謝謝。

+0

試試這個與阿爾法值 應用彩色濾光片http://stackoverflow.com/questions/5445085/understanding-colors-in-android-6-chars – Raj008

回答

0

是你必須定義每個按鈕和那些按鈕的onclick的顏色較深分配新的顏色較深

3

嘗試這個 -

button.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      v.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFFAA0000)); 

      } 


     } 

和清晰過濾器做到這一點

button.getBackground().clearColorFilter(); 
5

我假設您希望按鈕在觸摸時變暗,並在用戶釋放按鈕時恢復正常。

我建議創建一個自定義按鈕,它做的工作給你:

import android.content.Context; 
import android.graphics.LightingColorFilter; 
import android.util.AttributeSet; 
import android.view.MotionEvent; 
import android.widget.Button; 

public class DarkenButton extends Button { 

    public DarkenButton(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public DarkenButton(Context context) { 
     super(context); 
    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
     switch (event.getAction()) { 
     case MotionEvent.ACTION_DOWN: 
      // darken background 
      getBackground().setColorFilter(
        new LightingColorFilter(0xff888888, 0x000000)); 
      break; 

     case MotionEvent.ACTION_UP: 
      // clear color filter 
      getBackground().setColorFilter(null); 
      break; 
     } 
     return super.onTouchEvent(event); 
    } 

} 

然後使用DarkenButton任何地方,你通常會使用一個按鈕。

+0

假如有人使用覆蓋的解決方案在ImageView的,使用具有特定alpha的顏色(如#33445566),我應該將什麼放入LightingColorFilter的第一個參數中,以用此替換以前的解決方案? –

+0

@androiddeveloper我不認爲我理解。你如何實現覆蓋? – anakin78z

+0

只是當前視圖頂部的此視圖的容器中的另一個視圖。這會在當前視圖頂部創建一個半透明顏色層。 –