【问题标题】:How set Padding when an button is touched but the pointer is out of my button?当触摸按钮但指针不在我的按钮之外时如何设置填充?
【发布时间】:2020-11-28 07:49:49
【问题描述】:

我使用 XML 文件来显示具有 2 种状态(正常、按下)的按钮。我怎样才能 找出何时触摸按钮但光标不在?

我想要这样的按钮效果

按钮not被触摸

按钮touched

按钮被触摸但finger hasn't been lifted

这是我使用的 XML 文件:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/button_press" />
    <item android:drawable="@drawable/button_nopress" />
</selector>

这是我的 Java 类:

button = findViewById(R.id.b1);
button.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN){
                    button.setPadding(0, 55, 0, 0);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    button.setPadding(0, 0, 0, 0);
                }
                return false;
            }
        });            

这是我的代码按钮:

按钮被触摸但finger hasn't been lifted

【问题讨论】:

    标签: android android-studio material-design touch


    【解决方案1】:

    更新

    我可以用这段代码做到这一点:

    private Rect rect;    // Variable rect to hold the bounds of the view
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            // Construct a rect of the view's bounds
            rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
        }
        if(event.getAction() == MotionEvent.ACTION_MOVE){
            if(!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())){
                // User moved outside bounds
            }
        }
        return false;
    }
    

    【讨论】:

      【解决方案2】:

      看看下面的代码。

      <?xml version="1.0" encoding="utf-8"?>
      <selector xmlns:android="http://schemas.android.com/apk/res/android">
          <item android:drawable="@drawable/button_pressed"
                android:state_pressed="true" />
          <item android:drawable="@drawable/button_focused"
                android:state_focused="true" />
          <item android:drawable="@drawable/button_default" />
      </selector>
      

      属性 state_pressed 或 state_focused 应该可以完成这项工作。 请参阅以下link 以获得更多指导

      【讨论】:

      • 它不工作。 android:state_focused="true" 仅在使用键盘上的箭头键时有效。 :(
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      相关资源
      最近更新 更多