添加TextChanged和KeyPressed事件处理程序到EditText使OnBackPressed不命中



我一直在做一个有3个活动的应用程序(我们说A, B, C)

  1. A调用B使用StartActivity(typeof(B))
  2. B调用C使用StartActivity(typeof(C))和完成自己使用this.finish ()
  3. C在LinearLayout中有一个全屏的EditText。C也被重写了OnBackPressed调用this.finish()来完成自身并进行导航back to A[因为A仍在BackStack中]。在C的OnCreate方法中,EditText的eventandler增加了TextChanged event和KeyPressed如下所示:
public void OnCreate(Bundle SavedInstanceBundle) 
{
    base.OnCreate(SavedInstanceBundle);
    SetContentView(Resource.Layout.EditTextLayout);
    EditText editText = FindViewById<EditText>(Resource.Id.editText);
    //ADDING EVENT HANDLERS FOR EDITTEXT'S TEXTCHANGED AND KEYPRESSED EVENTS
    editText.TextChanged += editText_TextChanged;
    editText.KeyPressed += editText_KeyPressed;
}
private void editText_TextChanged (object sender, TextChangedEventArgs e)
{
}
private void editText_KeyPressed (object sender, View.KeyEventArgs e)
{
}
public override void OnBackPressed() 
{
    base.OnBackPressed();
    this.finish();
}

这里的问题是,当事件处理程序代码存在时,OnBackPressed是当Hardware back被按下时不会执行。但是,当添加事件处理程序代码被删除为两个事件,最终OnBackPressed启动正常工作。

你可以在KeyPressed事件处理程序中确定用户是否按了Back键:

private void editText_KeyPressed (object sender, View.KeyEventArgs e)
{
    if (e.KeyCode == Keycode.Back)
    {
        this.Finish();
        e.Handled = true;
        return;
    }
}

最新更新