android - ON_CANCEL 永远不会被调用

标签 android button ontouchlistener

所以我试图让我的按钮改变它的图像,当我按下它时它会正确改变,当我在按钮上抬起时确实调用了 ACTION_UP ......但是,当调用 ACTION_DOWN 并且我将手指移开时(外部)按钮并抬起,仍然调用 ACTION_UP。它应该将图像设置回正常状态并且不执行任何其他操作。

twitterBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent touchEvent) {
                switch(touchEvent.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                        twitterBtn.setBackgroundResource(R.drawable.logintwittertouched);
                        return true;
                    case MotionEvent.ACTION_CANCEL:
                        twitterBtn.setBackgroundResource(R.drawable.logintwitter);
                        return true;
                    case MotionEvent.ACTION_UP:
                        twitterBtn.setBackgroundResource(R.drawable.logintwitter);
                        try {
                            adapter.authorize(MainActivity.this, Provider.TWITTER);
                            dialog = ProgressDialog.show(MainActivity.this, "", "Connecting to Twitter", true);
                        } catch (Exception e) {
                            Log.v(getString(R.string.clickrerr), "" + e.toString());
                        }
                    return true;
                }
                return false;

            }

        });

最佳答案

用 XML 做:

  1. 创建 res/drawable/twitter_button.xml :

    <item android:drawable="@drawable/twitter_button_on" android:state_pressed="true"/>
    <item android:drawable="@drawable/twitter_button_off"/>
    

    它使用 2 个图像:twitter_button_on.pngtwitter_button_off.png ,您还应该将其放在 drawable 中文件夹。

  2. 在您的布局中,将此添加到您的 <Button> :

    android:background="@drawable/twitter_button"
    

关于android - ON_CANCEL 永远不会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18365824/

相关文章:

swift - 如何在 Storyboard中对齐两个 uibutton

android - 如何在android中单击按钮时隐藏和显示密码?

android - 绑定(bind)一个 View 以在 RelativeLayout 中拖动

android - 网格布局+ ScrollView

Android SQLite数据库递归查询

html - 我的按钮不工作

android - 单击后用按钮中的另一个图像替换图像

android - Android中连续 "Action_DOWN"

android - MvvmCross绑定(bind)+Android EventHandler

Android firebase 推送通知最低版本问题