【问题标题】:Changing the icon of a button when it is clicked and the activity doing something when focus of the button is lost单击按钮时更改按钮的图标,并在按钮焦点丢失时更改活动
【发布时间】:2013-11-28 14:24:37
【问题描述】:

我想在我的 android 应用程序中制作一个按钮,这样当我将手指放在按钮上(按钮获得焦点)时,按钮的图标应该会改变(通过 button.setBackgroundDrawable 或类似的东西)和当按钮失去焦点时(我将手指从它身上移开),它会执行它应该做的事情并且图标保持不变(转到另一个活动,检查smth,输入smth等等)。我不知道哪些功能会说明何时获得焦点以及何时失去焦点。有什么想法吗?

【问题讨论】:

  • 我们可以得到你的代码吗?!?
  • 使用onTouchListener

标签: java android android-layout android-fragments android-button


【解决方案1】:

在drawable中添加button_state.xml文件

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/onfocusonstatepressed" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/onstatepressed" />
<item android:state_focused="true" android:drawable="@drawable/onfocus"/>
<item android:state_focused="false" android:drawable="@drawable/normal" />
</selector>

接下来在你的主布局 xml 中为你的按钮添加一个属性

android:background="@drawable/button_state"

【讨论】:

    【解决方案2】:

    在触摸模式下您不会获得焦点。只要你触摸一个按钮,它就处于按下模式。焦点仅适用于具有硬件按钮(或鼠标)的设备,允许选择视图然后“按下”它。

    【讨论】:

      【解决方案3】:

      注册一个TouchListener到Button:

      button.setOnTouchListener(new ButtonDownListener());
      

      这里是你的听众

      public class ButtonDownListener implements OnTouchListener{
      
                 public boolean onTouch(View v, MotionEvent event){
                  if(event == MotionEvent.ACTION_DOWN){
                      //do your stuff
                  }
                  else if(event == MotionEvent.ACTION_UP){
                      //do your stuff
                  }
      
                  return true;
              }
          }
      

      【讨论】:

      • 如果您不打算添加功能,我建议您使用标准的 View.OnTouchListener 而不是实现它。
      【解决方案4】:

      你可以像这样使用 onTouchListener

      button.setOnTouchListener(new OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
          if(event.getAction() == MotionEvent.ACTION_UP){
      
              //This triggers when you lift your finger
          } else if(event.getAction() == MotionEvent.ACTION_DOWN) {
      
             //this triggers when you put your finger down
          }
          return false;
      }
      

      });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-06
        • 1970-01-01
        相关资源
        最近更新 更多