代码之家  ›  专栏  ›  技术社区  ›  mremremre1

对自定义按钮使用正确的MotionEvent

  •  0
  • mremremre1  · 技术社区  · 11 年前

    我正在制作一个应用程序,我想使用自定义按钮皮肤。按下按钮时,我用于更改背景的代码如下:

     button3.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN) {
                    button3.setBackgroundResource(R.drawable.blue_buttonn);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    button3.setBackgroundResource(R.drawable.black_buttonn);
                }else if (event.getAction() == MotionEvent.ACTION_HOVER_MOVE) {
                    button3.setBackgroundResource(R.drawable.black_buttonn);
                }
                return false;
            }
        });
    

    这个代码应该使按钮在按下时变为蓝色,释放时变为黑色。它可以工作,但如果单击按钮并将其拖离,则不会触发事件ACTION_UP。在这种情况下,我应该使用什么事件?

    我编辑了我的代码,添加了HOVER_MOVE事件,当你把手指从按钮上移开时,它就会工作。 但是,由于这些按钮位于自定义列表视图的项目内,如果将手指移到当前项目之外,则不会触发事件HOVER_move。

    enter image description here

    3 回复  |  直到 11 年前
        1
  •  3
  •   khubaib    11 年前

    试试这个

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">  
    
    <item     android:state_enabled="false"     
    android:drawable="@drawable/default_bgnd" />
    
    <item     android:state_focused="true"        
    android:drawable="@drawable/new_green" />
    
    <item     android:state_pressed="true"        
    android:drawable="@drawable/new_green" />
    
    <item     android:state_checked="true"        
    android:drawable="@drawable/new_green"/>
    
    <item     android:state_selected="true"        
    android:drawable="@drawable/new_green" /> 
    </selector> 
    

    将此xml放在drawables文件夹中,并将其设置为xml中按钮的背景 祝你好运

        2
  •  0
  •   Chintan Soni    11 年前

    尝试返回 true 而不是 false . True 指示侦听器消耗了 TouchEvent .

        3
  •  0
  •   khubaib    11 年前

    试试这个。

    onButton.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
    if(ParentalSet.equalsIgnoreCase("OFF")){
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
    ((TextView) v).setTextColor(0xFF000000);
    onButton.setBackgroundDrawable(getResources().getDrawable(buttonGlow));
    break;
    case MotionEvent.ACTION_UP:
    onButton.setTextColor(Color.parseColor                                                                 (OptimumConstants.CODE_000000));
    onButton.setBackgroundDrawable(getResources().getDrawable                                           (R.drawable.new_off));
    break;
    default:
    break;
     }
    }
    return false;
    }
    });