仅当平台为 Android 时才包含行

include line only if platform is Android

我遇到的一个问题是,当我导航到包含 android 上的表单的页面时,键盘会自动弹出。我找到了一个解决方案,但它只适用于 Android:

import { View } from "tns-core-modules/ui/core/view";

export class AutoFocusView extends View {

    createNativeView() {
        if (typeof android !== "undefined") {
            const linearLayout = new android.widget.LinearLayout(this._context);
            linearLayout.setFocusableInTouchMode(true);
            linearLayout.setFocusable(true);
            return linearLayout;
        } 
        return super.createNativeView();
    }

    onLoaded() {
        super.onLoaded();
        this.requestFocus();
    }

    requestFocus() {
        const nativeViewProtected = this.nativeViewProtected;
        nativeViewProtected.requestFocus();
    }
}

我用这个组件。但它只适用于 android,所以每次我想为 IOS 构建时,我都需要在我的代码中对其进行注释。我想知道有没有更简单的方法。

仅当平台为 Android 时才调用 requestFocus()

onLoaded() {
    super.onLoaded();
    if (typeof android !== "undefined") {
        this.requestFocus();
    }
}

您也可以将其编写为项目中的插件,在平台特定文件中将 iOS 和 Android 的代码分开。

你可以这样做:

import {isAndroid, isIOS} from '@nativescript/core';

然后在你的计算中:

isandroid() {
                return isAndroid;
            }

然后在您需要的任何方法中使用此标志:

if(isAndroid) {
  this.requestFocus();
}

如果需要与 v-if 一起使用,您也可以在模板中使用这个 isAndroid 标志。