Last active
May 11, 2020 08:35
-
-
Save dilipsuthar97/a968d885724e73705d3c211dfc2a87fd to your computer and use it in GitHub Desktop.
Android Native Module wrapper for ReactNative -MyLibraryModule.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.reactlibrary; | |
import android.graphics.Color; | |
import android.view.View; | |
import android.widget.TextView; | |
import android.widget.Toast; | |
import com.facebook.react.bridge.Callback; | |
import com.facebook.react.bridge.ReactApplicationContext; | |
import com.facebook.react.bridge.ReactContextBaseJavaModule; | |
import com.facebook.react.bridge.ReactMethod; | |
import com.facebook.react.bridge.ReadableMap; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.Map; | |
import androidx.annotation.NonNull; | |
import androidx.annotation.Nullable; | |
public class MyLibraryModule extends ReactContextBaseJavaModule { | |
private final ReactApplicationContext reactContext; | |
private static final String DURATION_TOAST_SHORT = "TOAST_SHORT"; | |
private static final String DURATION_TOAST_LONG = "TOAST_LONG"; | |
public MyLibraryModule(ReactApplicationContext reactContext) { | |
super(reactContext); | |
this.reactContext = reactContext; | |
} | |
// Methods | |
/** | |
* Show Toast ReactNative method | |
* @param options Toast options | |
*/ | |
@ReactMethod | |
public void showToast(ReadableMap options) { | |
String message = getOptionValue(options, "message", ""); | |
int duration = getOptionValue(options, "duration", Toast.LENGTH_SHORT); | |
Toast.makeText(reactContext, message, duration).show(); | |
} | |
// Module name in javascript to expose | |
@NonNull | |
@Override | |
public String getName() { | |
return "MyLibrary"; | |
} | |
// Constants in javascript to expose | |
@Nullable | |
@Override | |
public Map<String, Object> getConstants() { | |
final Map<String, Object> constants = new HashMap<>(); | |
constants.put(DURATION_TOAST_SHORT, Toast.LENGTH_SHORT); | |
constants.put(DURATION_TOAST_LONG, Toast.LENGTH_LONG); | |
return constants; | |
} | |
// Helpers | |
private String getOptionValue(ReadableMap option, String key, String fallBack) { | |
return option.hasKey(key) ? option.getString(key) : fallBack; | |
} | |
private int getOptionValue(ReadableMap option, String key, int fallBack) { | |
return option.hasKey(key) ? option.getInt(key) : fallBack; | |
} | |
private boolean getOptionValue(ReadableMap option, String key, boolean fallBack) { | |
return option.hasKey(key) ? option.getBoolean(key) : fallBack; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment