2017-07-24 76 views
1

我正在尝试使用软键盘的完成按钮通过数据绑定来激活一个方法。就像onClick。有没有办法做到这一点?在数据绑定中的键盘上使用完成按钮

例如:

<EditText    
    android:id="@+id/preSignUpPg2EnterPhone" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"  
    onOkInSoftKeyboard="@{(v) -> viewModel.someMethod()}" 
    /> 

onOkInSoftKeyboard不存在...有什么创造这种行为?

谢谢!

+0

你看起来像https://stackoverflow.com/questions/2004344/how-do-i-handle-imeoptions-done-button-click或者是一些别的东西? –

+0

这显然是别的......你提出的答案不使用数据绑定,它使用一个监听器。我想要数据绑定来激活一个行为。请不要投下一个问题,除非你确定它是重复的 –

+0

只是为了清楚我没有downvote你的问题..通过数据绑定什么你想要做什么仍然不清楚,请你说明你是什么试图达到(也会更好,如果你告诉我们你有什么尝试) –

回答

4

我不会声称是onEditorAction()或软键盘的专家。这就是说,假设你使用Firoz Memon建议的堆栈溢出问题的解决方案,你可以做到这一点。即使有另一种更好的解决方案,这也可以让你了解如何添加自己的事件处理程序。

你需要一个绑定适配器,它需要某种处理器。让我们假设你有一个空的听众是这样的:

public class OnOkInSoftKeyboardListener { 
    void onOkInSoftKeyboard(); 
} 

然后,你需要一个BindingAdapter:

@BindingAdapter("onOkInSoftKeyboard") // I like it to match the listener method name 
public static void setOnOkInSoftKeyboardListener(TextView view, 
     final OnOkInSoftKeyboardListener listener) { 
    if (listener == null) { 
     view.setOnEditorActionListener(null); 
    } else { 
     view.setOnEditorActionListener(new OnEditorActionListener() { 
      @Override 
      public void onEditorAction(TextView v, int actionId, KeyEvent event) { 
       // ... solution to receiving event 
       if (somethingOrOther) { 
        listener.onOkInSoftKeyboard(); 
       } 
      } 
     }); 
    } 
} 
+0

伟大的解决方案! –

0

您可以简单地使用的EditText动作完成的事件。

<EditText 
    android:id="@+id/preSignUpPg2EnterPhone" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:imeOptions="actionDone" 
    /> 
public class LoginActivity extends AppCompatActivity implements TextView.OnEditorActionListener { 

private ActivityLoginBinding binding; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    binding = DataBindingUtil.setContentView(this, R.layout.activity_login); 


    binding.preSignUpPg2EnterPhone.setOnEditorActionListener(this); 


} 

@Override 
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) { 
    switch (textView.getId()) { 
     case R.id.preSignUpPg2EnterPhone: 
      if (actionId == EditorInfo.IME_ACTION_DONE) { 
       // code 
      } 
      break; 
    } 
    return false;} 
} 
相关问题