0
# NativeScript Widgets
1
2
Platform-specific NativeScript widget declarations for Android development, including custom transitions, async utilities for HTTP requests, file operations, and image processing. These widgets extend standard Android functionality with NativeScript-specific features.
3
4
## Capabilities
5
6
### Custom Transitions
7
8
NativeScript custom transition support for enhanced Android UI animations.
9
10
```typescript { .api }
11
declare module org.nativescript.widgets {
12
/**
13
* Custom transition class extending AndroidX Visibility transition
14
*/
15
export class CustomTransition extends androidx.transition.Visibility {
16
/**
17
* Create a custom transition with animator set and name
18
* @param animatorSet - Android AnimatorSet for the transition
19
* @param transitionName - Name identifier for the transition
20
*/
21
constructor(animatorSet: android.animation.AnimatorSet, transitionName: string);
22
23
/**
24
* Set whether to reset on transition end
25
* @param resetOnTransitionEnd - Whether to reset when transition completes
26
*/
27
public setResetOnTransitionEnd(resetOnTransitionEnd: boolean): void;
28
29
/**
30
* Get the transition name identifier
31
* @returns The transition name string
32
*/
33
public getTransitionName(): string;
34
}
35
}
36
```
37
38
**Usage Examples:**
39
40
```typescript
41
// Create custom transition
42
const animatorSet = new android.animation.AnimatorSet();
43
// Configure animators...
44
const transition = new org.nativescript.widgets.CustomTransition(animatorSet, "fadeIn");
45
46
// Configure transition behavior
47
transition.setResetOnTransitionEnd(true);
48
49
// Get transition information
50
const name = transition.getTransitionName();
51
console.log(`Transition name: ${name}`);
52
```
53
54
### Async Operations
55
56
Comprehensive async operation support with completion callbacks for various operations.
57
58
```typescript { .api }
59
declare module org.nativescript.widgets.Async {
60
/**
61
* Callback interface for async operations
62
*/
63
export interface ICompleteCallback {
64
/**
65
* Called when operation completes successfully
66
* @param result - The operation result
67
* @param context - Optional context object
68
*/
69
onComplete(result: Object, context: Object): void;
70
71
/**
72
* Called when operation fails with error
73
* @param error - Error message string
74
* @param context - Optional context object
75
*/
76
onError(error: string, context: Object): void;
77
}
78
79
/**
80
* Concrete callback implementation for async operations
81
*/
82
export class CompleteCallback {
83
/**
84
* Create callback with implementation
85
* @param implementation - ICompleteCallback implementation
86
*/
87
constructor(implementation: ICompleteCallback);
88
89
/**
90
* Handle successful completion
91
* @param result - Operation result
92
* @param context - Optional context
93
*/
94
onComplete(result: Object, context: Object): void;
95
96
/**
97
* Handle error condition
98
* @param error - Error message
99
* @param context - Optional context
100
*/
101
onError(error: string, context: Object): void;
102
}
103
}
104
```
105
106
**Usage Examples:**
107
108
```typescript
109
// Create async callback
110
const callback = new org.nativescript.widgets.Async.CompleteCallback({
111
onComplete: (result, context) => {
112
console.log("Operation successful:", result);
113
},
114
onError: (error, context) => {
115
console.error("Operation failed:", error);
116
}
117
});
118
119
// Use with async operations (examples below)
120
```
121
122
### Image Operations
123
124
Async image download and processing utilities.
125
126
```typescript { .api }
127
declare module org.nativescript.widgets.Async.Image {
128
/**
129
* Download image from URL asynchronously
130
* @param url - Image URL to download
131
* @param callback - Completion callback for success/error
132
* @param context - Optional context object passed to callback
133
*/
134
export function download(url: string, callback: CompleteCallback, context: any);
135
}
136
```
137
138
**Usage Examples:**
139
140
```typescript
141
// Download image asynchronously
142
const imageCallback = new org.nativescript.widgets.Async.CompleteCallback({
143
onComplete: (result, context) => {
144
// result contains downloaded image data
145
console.log("Image downloaded successfully");
146
// Process image result...
147
},
148
onError: (error, context) => {
149
console.error("Image download failed:", error);
150
}
151
});
152
153
org.nativescript.widgets.Async.Image.download(
154
"https://example.com/image.jpg",
155
imageCallback,
156
{ requestId: "img001" }
157
);
158
```
159
160
### File Operations
161
162
Async file read and write operations with encoding support.
163
164
```typescript { .api }
165
declare module org.nativescript.widgets.Async.File {
166
/**
167
* Read text file asynchronously with encoding
168
* @param path - File path to read
169
* @param encoding - Text encoding (e.g., "UTF-8")
170
* @param callback - Completion callback
171
* @param context - Optional context object
172
*/
173
export function readText(path: string, encoding: string, callback: CompleteCallback, context: any);
174
175
/**
176
* Read binary file asynchronously
177
* @param path - File path to read
178
* @param callback - Completion callback
179
* @param context - Optional context object
180
*/
181
export function read(path: string, callback: CompleteCallback, context: any);
182
183
/**
184
* Write text file asynchronously with encoding
185
* @param path - File path to write
186
* @param content - Text content to write
187
* @param encoding - Text encoding (e.g., "UTF-8")
188
* @param callback - Completion callback
189
* @param context - Optional context object
190
*/
191
export function writeText(path: string, content: string, encoding: string, callback: CompleteCallback, context: any);
192
193
/**
194
* Write binary file asynchronously
195
* @param path - File path to write
196
* @param content - Binary content as native array
197
* @param callback - Completion callback
198
* @param context - Optional context object
199
*/
200
export function write(path: string, content: native.Array<number>, callback: CompleteCallback, context: any);
201
}
202
```
203
204
**Usage Examples:**
205
206
```typescript
207
// Read text file
208
const readCallback = new org.nativescript.widgets.Async.CompleteCallback({
209
onComplete: (result, context) => {
210
console.log("File content:", result);
211
},
212
onError: (error, context) => {
213
console.error("File read error:", error);
214
}
215
});
216
217
org.nativescript.widgets.Async.File.readText(
218
"/path/to/file.txt",
219
"UTF-8",
220
readCallback,
221
null
222
);
223
224
// Write text file
225
const writeCallback = new org.nativescript.widgets.Async.CompleteCallback({
226
onComplete: (result, context) => {
227
console.log("File written successfully");
228
},
229
onError: (error, context) => {
230
console.error("File write error:", error);
231
}
232
});
233
234
org.nativescript.widgets.Async.File.writeText(
235
"/path/to/output.txt",
236
"Hello NativeScript!",
237
"UTF-8",
238
writeCallback,
239
null
240
);
241
242
// Read binary file
243
org.nativescript.widgets.Async.File.read(
244
"/path/to/image.png",
245
readCallback,
246
{ fileType: "image" }
247
);
248
249
// Write binary file
250
const binaryData = new native.Array<number>();
251
// Populate binaryData...
252
org.nativescript.widgets.Async.File.write(
253
"/path/to/output.bin",
254
binaryData,
255
writeCallback,
256
null
257
);
258
```
259
260
### HTTP Operations
261
262
Async HTTP request functionality with comprehensive configuration options.
263
264
```typescript { .api }
265
declare module org.nativescript.widgets.Async.Http {
266
/**
267
* Key-value pair for HTTP headers and parameters
268
*/
269
export class KeyValuePair {
270
/** Header/parameter key */
271
public key: string;
272
/** Header/parameter value */
273
public value: string;
274
275
/**
276
* Create key-value pair
277
* @param key - The key string
278
* @param value - The value string
279
*/
280
constructor(key: string, value: string);
281
}
282
283
/**
284
* HTTP request configuration options
285
*/
286
export class RequestOptions {
287
/** Request URL */
288
public url: string;
289
/** HTTP method (GET, POST, etc.) */
290
public method: string;
291
/** HTTP headers as key-value pairs */
292
public headers: java.util.ArrayList<KeyValuePair>;
293
/** Request body content */
294
public content: java.nio.ByteBuffer;
295
/** Request timeout in milliseconds */
296
public timeout: number;
297
/** Screen width for responsive requests */
298
public screenWidth: number;
299
/** Screen height for responsive requests */
300
public screenHeight: number;
301
/** Whether to follow HTTP redirects */
302
public dontFollowRedirects: boolean;
303
}
304
305
/**
306
* HTTP response result containing response data and metadata
307
*/
308
export class RequestResult {
309
/** HTTP status code (200, 404, etc.) */
310
public statusCode: number;
311
/** Response body content as string */
312
public content: string;
313
/** Response headers as key-value pairs */
314
public headers: java.util.ArrayList<KeyValuePair>;
315
/** Error message if request failed */
316
public error: string;
317
/** Request URL that was executed */
318
public url: string;
319
/** Whether the request completed successfully */
320
public isSuccess: boolean;
321
/** Total request time in milliseconds */
322
public responseTime: number;
323
}
324
}
325
```
326
327
**Usage Examples:**
328
329
```typescript
330
// Create HTTP request options
331
const options = new org.nativescript.widgets.Async.Http.RequestOptions();
332
options.url = "https://api.example.com/data";
333
options.method = "GET";
334
options.timeout = 10000; // 10 seconds
335
options.dontFollowRedirects = false;
336
337
// Add headers
338
options.headers = new java.util.ArrayList<org.nativescript.widgets.Async.Http.KeyValuePair>();
339
options.headers.add(new org.nativescript.widgets.Async.Http.KeyValuePair("Accept", "application/json"));
340
options.headers.add(new org.nativescript.widgets.Async.Http.KeyValuePair("User-Agent", "NativeScript-App"));
341
342
// Add request body for POST
343
if (options.method === "POST") {
344
const requestData = JSON.stringify({ key: "value" });
345
const bytes = new java.lang.String(requestData).getBytes("UTF-8");
346
options.content = java.nio.ByteBuffer.wrap(bytes);
347
}
348
349
// Set screen dimensions for responsive requests
350
options.screenWidth = 375;
351
options.screenHeight = 667;
352
353
// Use with HTTP request function
354
const httpCallback = new org.nativescript.widgets.Async.CompleteCallback({
355
onComplete: (result: org.nativescript.widgets.Async.Http.RequestResult, context) => {
356
console.log("HTTP request successful");
357
console.log(`Status: ${result.statusCode}`);
358
console.log(`Response time: ${result.responseTime}ms`);
359
console.log(`Content: ${result.content}`);
360
361
// Process response headers
362
for (let i = 0; i < result.headers.size(); i++) {
363
const header = result.headers.get(i);
364
console.log(`Header: ${header.key} = ${header.value}`);
365
}
366
367
// Parse JSON response if applicable
368
if (result.isSuccess && result.statusCode === 200) {
369
try {
370
const data = JSON.parse(result.content);
371
// Process parsed data...
372
} catch (parseError) {
373
console.error("Failed to parse JSON response:", parseError);
374
}
375
}
376
},
377
onError: (error, context) => {
378
console.error("HTTP request failed:", error);
379
if (context) {
380
console.log("Request context:", context);
381
}
382
}
383
});
384
385
// Note: Actual HTTP request function would be provided by NativeScript runtime
386
// This shows the complete data structures available for HTTP operations
387
```
388
389
## Integration with NativeScript
390
391
These widgets are specifically designed for NativeScript Android applications and provide:
392
393
### Enhanced Android Integration
394
- Native Android transition support with AndroidX compatibility
395
- Direct integration with Android animation framework
396
- Platform-specific performance optimizations
397
398
### Async Operation Patterns
399
- Consistent callback-based async API across all operations
400
- Error handling with detailed error messages
401
- Context passing for operation tracking
402
403
### File System Access
404
- Async file operations to prevent UI blocking
405
- Encoding support for text operations
406
- Binary file support for media and data files
407
408
### Network Operations
409
- Comprehensive HTTP request configuration
410
- Header and parameter management
411
- Timeout and redirect control
412
- Screen dimension awareness for responsive requests
413
414
## Performance Considerations
415
416
- **Async Operations**: All widget operations are asynchronous to maintain UI responsiveness
417
- **Memory Management**: Use proper callback lifecycle management
418
- **Error Handling**: Always implement both success and error callbacks
419
- **Context Usage**: Use context parameters for operation tracking and cleanup
420
421
## Error Handling Patterns
422
423
```typescript
424
// Robust error handling pattern
425
const safeCallback = new org.nativescript.widgets.Async.CompleteCallback({
426
onComplete: (result, context) => {
427
try {
428
// Process result safely
429
console.log("Operation completed:", result);
430
} catch (error) {
431
console.error("Error processing result:", error);
432
}
433
},
434
onError: (error, context) => {
435
// Log error and handle gracefully
436
console.error("Operation failed:", error);
437
if (context) {
438
console.log("Context information:", context);
439
}
440
// Implement fallback behavior
441
}
442
});
443
```