edittext焦点不允许我做onKeyBack

时间:2017-03-01 12:37:11

标签: android android-fragments android-edittext

我已经以这种方式实现了我的片段:每次用户点击后退按钮时,它都会执行此功能:

public void onResume()
{
    super.onResume();

    if(getView() == null)
    {
        return;
    }

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK)
            {
                Fragment fragment = new FlightPerformanceFragment();

                manager.beginTransaction().replace(R.id.content_main,fragment).commit();

                Log.e("resume","resume FlightPerformance");
                return true;
            }
            return false;
        }
    });
}

如果没有editText聚焦,这很有效。 我搜索了很多,我尝试用这种方式解决这个问题,使用OnKeyListener

 View.OnKeyListener onKeyListener = new View.OnKeyListener()
    {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if (event.getAction() == KeyEvent.ACTION_DOWN)
            {
                //check if the right key was pressed
                if (keyCode == KeyEvent.KEYCODE_BACK)
                {
                    if(v == tasET)
                        tasET.clearFocus();
                    else if(v == rhoET)
                        rhoET.clearFocus();

                    return true;
                }
            }
            return false;
        }
    };

 tasET = (EditText) rootView.findViewById(R.id.paisaET);
 tasET.setOnKeyListener(onKeyListener);

问题在于,有时clearFocus()方法会转回上一个editText,并且不会清除每个editText的焦点。

因此,如果这个方法看起来有点复杂做简单的后退操作(我不能使用onBackPressed(),因为我需要替换其他片段),还有最简单的方法吗?

谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

创建一个客户Edittext并在软键盘上执行后退单击操作

public class MyEdittext extends EditText
{
public MybusinessEdittext(Context context, AttributeSet attrs) {
    super(context, attrs);
}

private KeyImeChange keyImeChangeListener;

public void setKeyImeChangeListener(KeyImeChange listener) {
    keyImeChangeListener = listener;
}

public interface KeyImeChange {
    void onKeyIme(int keyCode, KeyEvent event);
}

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if (keyImeChangeListener != null) {
        keyImeChangeListener.onKeyIme(keyCode, event);
    }
    return false;
}
}


//perform back click action on soft keyboard 
myEdittext.setKeyImeChangeListener(new MybusinessEdittext.KeyImeChange() {
        @Override
        public void onKeyIme(int keyCode, KeyEvent event) {
            if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
                //do something here
            }
        }`