3

I am trying to access android's R object in NativeScript with Angular but I haven't had any success. The instructions here say to do it like this:

android.R.color.holo_purple

But when I try to import the android variable from the application module or the tns-core-modules/platform module I get an error that the R property on the android object is undefined. How do I get access to R?

Graham
  • 5,488
  • 13
  • 57
  • 92

3 Answers3

4

you don't need to import android variable from application module. it is automatically available by default at runtime. to remove compile time error property doesn't exists just declare the variable named android to any.

for example.

declare var android:any;
export class AppComponent{
  let holoPurple=android.R.color.holo_purple;
}
bhavin jalodara
  • 1,470
  • 9
  • 12
3

Couldn't get existing answers to work in latest nativescript / angular. I resolved it with the following:

Created a file App_Resources/Android/values/keys.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="key_name">xxxxxx</string>
</resources>

Import these

import * as app from 'tns-core-modules/application';
import * as utils from 'tns-core-modules/utils/utils';

then to grab the string

const context = app.android.context;
const res = context.getResources().getString(utils.ad.resources.getStringId('key_name'));
Horse
  • 3,023
  • 5
  • 38
  • 65
  • Thank you, I managed to use following `import * as application from "@nativescript/core/application"; import * as utils from "@nativescript/core/utils";` – elliotching May 07 '21 at 09:33
0

The android here is the main namespace for the Android SDK and not the android property from the application module.

See this StackOverflow answer for instruction on how to access the native SDK via TypeScript or use the instruction from the related documentation article

Nick Iliev
  • 9,610
  • 3
  • 35
  • 89
  • I did this but am still not able to access `android.R`. I am able to use the it when creating a new object like this `let myObj = new android.native.sdk.class.Example`. That works just fine. But if I try to use `android.R.color.Red` without the `new` keyword by passing it to a function or setting it to a property it doesn't work. – Graham Jul 09 '18 at 13:00
  • Check this comment on how to access a resource file via the `application` module https://github.com/NativeScript/android-runtime/issues/260#issuecomment-169361745 – Nick Iliev Jul 09 '18 at 13:27