This is the image of project structure in Android studio:
This is the image of project structure of nativescript project:
As you see they are same. so we can write java code in nativescript as we write in android studio.
We want to Add Toast to the default app of nativescript.
after creating a new nativescript project create a directory the java/org/example
directory like this:
create a new MyToast.java
file in example
directory;
MyToast.java:
package org.example;
import android.widget.Toast;
import android.content.Context;
public class MyToast{
public static void showToast(Context context,String text ,String StrDuration ){
int duration;
switch (StrDuration){
case "short":
duration = Toast.LENGTH_SHORT;
break;
case "long":
duration = Toast.LENGTH_LONG;
break;
}
Toast.makeText(context,text, Toast.LENGTH_SHORT).show();
}
}
Notes: don't forget the package name;
app.component.ts:
import {Component} from "@angular/core";
let application = require("application");
declare var org: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--;
org.example.MyToast.showToast(application.android.context,"You pressed the button","short");
}
}
now when you press the button it will show a toast;
Notes:
Toast.makeText
an we passed a context to it in this way :application.android.context
org
is, so we declared it: declare var org:any;