在 javascript 中直接使用 native apis
我们想要将 Toast 添加到 nativescript 默认应用程序。
import {Component} from "@angular/core";
let application = require("application");
declare var android:any;
@Component({
selector: "my-app",
templateUrl: "app.component.html",
})
export class AppComponent {
public counter: number = 16;
public get message(): string {
if (this.counter > 0) {
return this.counter + " taps left";
} else {
return "Hoorraaay! \nYou are ready to start building!";
}
}
public onTap() {
this.counter--;
this.showToast("You pressed the button","short");
}
public showToast(text:string ,StrDuration:string ):void{
let duration:number;
switch (StrDuration){
case "short":
duration = android.widget.Toast.LENGTH_SHORT;
break;
case "long":
duration = android.widget.Toast.LENGTH_LONG;
break;
}
android.widget.Toast.makeText(application.android.context,text, android.widget.Toast.LENGTH_SHORT).show();
}
}
为了创建吐司我们应该叫 Toast.makeText
,它在 android.widget.Toast
包中。Toast.makeText
接受上下文作为第一个参数,我们可以用这种方式获取 nativescript 中的上下文:application.android.context