簡體   English   中英

Android數據綁定view.onTouchListener

[英]Android data binding view.onTouchListener

Android中的數據綁定有

<Button android:onClick="@{handler.someButtonClick()}"/>

並且在它的Handler class它的監聽器會Handler class像:

public View.OnClickListener someButtonClick() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        };
    }

我想為一個Button實現OnTouchListener ,我可以知道按鈕何時被按下以及何時被釋放

喜歡:

// Check if the button is PRESSED
if (event.getAction() == MotionEvent.ACTION_DOWN){
     //do some thing          
}// Check if the button is RELEASED
else if (event.getAction() == MotionEvent.ACTION_UP) {
    //do some thing                     
}

有沒有可能的方法來完成這個任務。

這是您可以用來執行此操作的解決方法。

@BindingAdapter("touchListener")
public void setTouchListener(View self,boolean value){
    self.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            // Check if the button is PRESSED
            if (event.getAction() == MotionEvent.ACTION_DOWN){
                //do some thing
            }// Check if the button is RELEASED
            else if (event.getAction() == MotionEvent.ACTION_UP) {
                //do some thing
            }
            return false;
        }
    });
}

然后在 xml

<Button  app:touchListener="@{true}"/>

視圖模型

public class RecyclerViewModel   {
      public View.OnTouchListener onTouchListener;

      public void setOnTouchListener( View.OnTouchListener onTouchListener) {
          this.onTouchListener = onTouchListener;
      }
}

數據綁定

@BindingAdapter("onTouchListener")
public static void setOnTouchListener(View view, View.OnTouchListener onTouchListener) {
    if (onTouchListener != null)
        view.setOnTouchListener(onTouchListener);
}

在 xml 中使用

<Button app:onTouchListener="@{viewModel.onTouchListener}"/>

視圖模型

private var tapTime: Long = 0

fun onTouchListener(view:View, event: MotionEvent): Boolean {
   when (event.action) {
      MotionEvent.ACTION_DOWN -> {
          tapTime = Date().time
          // more commands for touch down event
      } 
      MotionEvent.ACTION_UP -> {
         if (Date().time - tapDate < 300) {
            view.performClick()
           // more commands if click event
         } else {
           // any commands if holded toch on screen
         } 
     }
  }
  return true
}

不需要數據綁定適配器。 它已經存在。

XML

<Button
   ...
   app:onTouchListener="@{viewModel.onTouchListener}"
   ...
  />

警告您需要在 ViewModel 中使用正確的簽名:

fun name(view:View, event: MotionEvent): Boolean

和 XML 中屬性的正確名稱:

app:onTouchListener

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM