Android 在片段中实现onKeyPreIme(intkeycode,KeyEvent事件)

Android 在片段中实现onKeyPreIme(intkeycode,KeyEvent事件),android,fragment,android-softkeyboard,Android,Fragment,Android Softkeyboard,我不知道如何在片段中实现onKeyPreIme(int-keyCode,KeyEvent-event) @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { // do your stu

我不知道如何在
片段中实现
onKeyPreIme(int-keyCode,KeyEvent-event)

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && 
        event.getAction() == KeyEvent.ACTION_UP) {
            // do your stuff
            return false;
    }
    return super.dispatchKeyEvent(event);
}

我试了很多,但都不管用。此外,我在谷歌或堆栈溢出上也找不到任何东西。我想在按下后退键且软键盘打开时执行一个操作。在my
EditText
s上设置
onKeyListener
不起作用,因为软键盘启动时不会调用
KeyEvent.KEYCODE\u BACK
。非常感谢您提供的帮助和源代码。

我无法理解如何实现onKeyPreIME,但我能够在键盘消失后执行一个操作,代码如下:

您需要更改比较高度差>200。这个比较对我很有用,因为我有一个滚动视图

fragmentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            if(getView() != null){
                int heightDiff = getView().getRootView().getHeight() - getView().getHeight();
                if (heightDiff < 200) { 
                    rlupdate.setVisibility(RelativeLayout.VISIBLE);
                }
                else {
                    rlupdate.setVisibility(RelativeLayout.GONE);
                }   
            }
        }
    });
fragmentView.getViewTreeObserver().addOnGlobalLayoutListener(新OnGlobalLayoutListener()){
@凌驾
公共图书馆{
如果(getView()!=null){
int-heightDiff=getView().getRootView().getHeight()-getView().getHeight();
如果(高度差<200){
rlupdate.setVisibility(RelativeLayout.VISIBLE);
}
否则{
rlupdate.setVisibility(RelativeLayout.GONE);
}   
}
}
});

我能够通过对与键盘输入相关的EditText视图进行子分类来实现onKeyPreIme。目标是创建一个自定义的锁屏,用户必须输入密码或离开应用程序。当用户点击“键盘向下”按钮时,键盘不会消失

确保为子类EditText创建单独的.java文件。此外,请确保在下面的代码中使用构造函数(必须通过AttrubuteSet)

我意识到我的onKeyPreIme实现可能与您的不匹配,但是它确实演示了如何在InputMethodManager执行它之前拦截键盘事件

我希望这有帮助

用户锁定活动屏幕截图

EditText子类

public class LockEditText extends EditText {
    /* Must use this constructor in order for the layout files to instantiate the class properly */
    public LockEditText(Context context, AttributeSet attrs) 
    {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    public boolean onKeyPreIme (int keyCode, KeyEvent event)
    {
        // Return true if I handle the event:
            // In my case i want the keyboard to not be dismissible so i simply return true
            // Other people might want to handle the event differently
        System.out.println("onKeyPreIme " +event);
        return true;
    }

}
UserLockActivity.java

public class UserLockActivity extends Activity 
{
    private LockEditText editText1;
    private LockEditText editText2;
    private LockEditText editText3;
    private LockEditText editText4;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_lock);
        editText1 = (LockEditText) findViewById(R.id.lock_text_1);
        editText2 = (LockEditText) findViewById(R.id.lock_text_2);
        editText3 = (LockEditText) findViewById(R.id.lock_text_3);
        editText4 = (LockEditText) findViewById(R.id.lock_text_4);
        setupTextChangedListener(editText1);
        setupTextChangedListener(editText2);
        setupTextChangedListener(editText3);
        setupTextChangedListener(editText4);
        // A method to bring out the keyboard when the view appears
        setFocusOnEditText(editText1);
    }

    public void setFocusOnEditText(LockEditText editText)
    {
        editText.clearFocus();
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
    }
    public void setupTextChangedListener(LockEditText editText)
    {
        editText.addTextChangedListener(new TextWatcher() 
        {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) 
            {

            }

            @Override
            public void afterTextChanged(Editable arg0) 
            {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) 
            {
                // TODO Auto-generated method stub
            }
        });
    }
}
activity\u user\u lock.xml布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".UserLockActivity" >

    <TextView
        android:id="@+id/main_lock_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        android:paddingTop="60dp"
        android:paddingBottom="20dp"
        android:text="@string/enter_passcode"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <LinearLayout
        android:id="@+id/lock_input_layout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_below="@+id/main_lock_text"
        android:orientation="horizontal" >

        <com.yourpackage.yourappname.LockEditText
            android:id="@+id/lock_text_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="numberPassword"
            android:textSize="30sp"
            android:gravity="center_horizontal"
            android:textStyle="bold" >
        </com.yourpackage.yourappname.LockEditText>
        <com.yourpackage.yourappname.LockEditText
            android:id="@+id/lock_text_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="numberPassword"
            android:textSize="30sp"
            android:gravity="center_horizontal"
            android:textStyle="bold" >
        </com.yourpackage.yourappname.LockEditText>
        <com.yourpackage.yourappname.LockEditText
            android:id="@+id/lock_text_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="numberPassword"
            android:textSize="30sp" 
            android:gravity="center_horizontal"
            android:textStyle="bold">
        </com.yourpackage.yourappname.LockEditText>
        <com.yourpackage.yourappname.LockEditText
            android:id="@+id/lock_text_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="numberPassword"
            android:textSize="30sp"
            android:gravity="center_horizontal"
            android:textStyle="bold" >
        </com.yourpackage.yourappname.LockEditText>
    </LinearLayout>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/lock_input_layout"
        android:layout_centerHorizontal="true"
        android:text="text" />

</RelativeLayout>

这是我的解决方案,对我来说效果非常好,但每个人的需求都不同

首先,我将EditText子类化并连接了一个侦听器(Google应该将其设置为默认设置)

然后,您可以从任何位置连接侦听器,如下所示:

myListenerEditText.setKeyImeChangeListener(new KeyImeChange() {

    @Override
    public void onKeyIme(int keyCode, KeyEvent event) {
        // All keypresses with the keyboard open will come through here!
        // You could also bubble up the true/false if you wanted 
        // to disable propagation.
    }
});

这是Deminetix提供的更完整的答案代码

我用Deminetix的答案在android上过滤手持式条形码阅读器,并得到结果

为了使其仅在带有按钮的屏幕上可用,我添加了一个带有android:textColor=“#FF000000”android:background=“#00FFFFFF”android:enabled=“false”的EditText 禁用的EditText仍会获取键盘事件

(可选)我可以使用以下命令隐藏软件键盘,但在禁用EditText后,它不是必需的

//InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//imm.showSoftInput(textPatientId, InputMethodManager.HIDE_IMPLICIT_ONLY);
MainActivity.java:

package com.doodkin.keyboardtest;

import com.doodkin.keyboardtest.ListenerEditText.KeyImeChange;

import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.KeyListener;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;

public class MainActivity extends Activity {
    private static final String TAG = "keyboard test";
    //private EditText editText1;

    ListenerEditText editText1=null;
    public String barcodebuffer="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText1 = (ListenerEditText) findViewById(R.id.editText1);

        editText1.setKeyImeChangeListener(new KeyImeChange() {

            @Override
            public boolean onKeyIme(int keyCode, KeyEvent event) {
                String deviceName=event.getDevice().getName();
                int keyboardType=event.getDevice().getKeyboardType();
                int indexof=deviceName.indexOf("USB");
                if(indexof!=-1 && keyboardType==InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
                {
                    if(event.getKeyCode()==KeyEvent.KEYCODE_ENTER)
                     {
                         if(barcodebuffer!="")
                         {
                             Log.d(TAG, "filterBarcodeKeys Chars Flush: " + barcodebuffer );
                             barcodebuffer="";
                         }
                     }
                     else
                     {

                         barcodebuffer+=Character.toString((char)event.getUnicodeChar());
                         //Log.d(TAG, "filterBarcodeKeys Char: " + Character.toString((char)event.getUnicodeChar()) );
                     }
                     return true;
                }
                return false;
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


}
activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <com.doodkin.keyboardtest.ListenerEditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:ems="10" >

        <requestFocus />
    </com.doodkin.keyboardtest.ListenerEditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="69dp"
        android:text="Button" />

</RelativeLayout>

这与我的初衷不符,但你的想法很有创意,所以我会接受你的回答superwealth@i2097i。谢谢,伙计:)@i2097i我有一个问题。android中是否有任何方法可以通过编程方式将焦点从
EditText
中移除?@Perry此解决方案运行良好,但它适用于活动。要添加到片段,必须在实例化InputMethodManager时获取活动。所以对于这一行:InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT\u METHOD\u SERVICE);添加一个getActivity。在getSystemService之前。所以它看起来是这样的:InputMethodManager imm=(InputMethodManager)getActivity().getSystemService(Context.INPUT\u METHOD\u SERVICE);感谢您的代码,了解返回
super.dispatchKeyEvent(event)活动的后退按钮将起作用!这看起来是最好的答案,因为它实际上支持覆盖onKeyPreIme。我不想问,但我很难让它工作。我扩展了AutoCompleteTextView,并在我的活动(您的第二个代码块)中的onKeyIme(…)中添加了一个return语句。除此之外,我完全复制了您的代码,并在“return”语句和新类中的每个方法上设置了断点。调用setKeyImeChangeListener并初始化keyImeChangeListener,但是,当按下某个键时,永远不会调用onKeyIme()。知道从哪里开始故障排除吗?好的,我想我明白了。这些键盘事件用于物理键盘,而不是软键盘。有人能证实吗?谢谢。顺便说一句,我还是Android的学生,所以谢谢你的代码。我能够使用它覆盖onfilterplete方法。Android没有为这些事件提供侦听器似乎有点傻。我也没有看到我的onKeyIme方法被调用。这适用于软键盘吗?我找不到setKeyImeChangeListener方法。它属于-public类ListenerEditText扩展了EditText。这是我的课程,我已经开发了你可以看到上面。坦白说,那是很久以前的事了,我不知道我能帮你什么忙。我不记得了。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <com.doodkin.keyboardtest.ListenerEditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:ems="10" >

        <requestFocus />
    </com.doodkin.keyboardtest.ListenerEditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="69dp"
        android:text="Button" />

</RelativeLayout>
package com.doodkin.keyboardtest;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;

/*
 * example: 

 myListenerEditText.setKeyImeChangeListener(new KeyImeChange() {

    @Override
    public boolean onKeyIme(int keyCode, KeyEvent event) {
        // All keypresses with the keyboard open will come through here!
        // You could also bubble up the true/false if you wanted 
        // to disable propagation.
    }
});

 */

public class ListenerEditText extends EditText {

    private KeyImeChange keyImeChangeListener;

    public ListenerEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

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

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

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