Nativescript/Angular中TextField绑定blur事件点击安卓键盘收起按钮不触发问题
问题根因
安卓系统原生行为下,点击软键盘自带的收起按钮不会主动让输入框失去焦点,因此TextField绑定的blur事件不会触发,属于正常系统行为,并非代码逻辑错误。
解决方案
通过监听安卓根布局的全局布局变化判断键盘收起状态,无需引入第三方插件,实现代码如下:
第一步:修改chat.component.ts代码
首先导入依赖、增加生命周期处理和监听逻辑:
import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'; import { isAndroid, Page } from '@nativescript/core'; @Component({ // 保留你的原有组件配置 }) export class ChatComponent implements OnInit, OnDestroy { @ViewChild('textInput') textInput: ElementRef; chatListHeight = "92"; private layoutChangeListener: any; private lastVisibleHeight = 0; constructor(private page: Page) {} ngOnInit() { // 仅安卓环境添加监听 if (isAndroid) { const rootView = this.page.android as android.view.View; this.layoutChangeListener = new android.view.ViewTreeObserver.OnGlobalLayoutListener({ onGlobalLayout: () => { const rect = new android.graphics.Rect(); // 获取当前窗口可见区域 rootView.getWindowVisibleDisplayFrame(rect); const currentVisibleHeight = rect.height(); if (this.lastVisibleHeight > 0) { // 可见区域高度增加超过阈值,判定为键盘收起 if (currentVisibleHeight - this.lastVisibleHeight > 100) { this.lowerInput(); // 若需要输入框同步失焦可打开下方注释 // this.textInput.nativeElement.dismissSoftInput(); } } this.lastVisibleHeight = currentVisibleHeight; } }); rootView.getViewTreeObserver().addOnGlobalLayoutListener(this.layoutChangeListener); } } ngOnDestroy() { // 组件销毁时移除监听器,避免内存泄漏 if (isAndroid && this.layoutChangeListener) { const rootView = this.page.android as android.view.View; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this.layoutChangeListener); } else { rootView.getViewTreeObserver().removeGlobalOnLayoutListener(this.layoutChangeListener); } } } // 保留你的原有方法 raiseInput() { console.log('focus'); this.chatListHeight = "50" } lowerInput() { console.log('blur'); this.chatListHeight = "92" } sendMsg(event) { // 保留你的原有发送逻辑 } }
第二步:原有HTML代码无需修改
原有的TextField绑定逻辑可以保留,focus、blur事件依旧可以正常响应其他场景下的输入框焦点变化。
内容的提问来源于stack exchange,提问作者J.V
相关产品推荐
相关产品推荐

