在 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