fresco | Android library for managing images | Android library
kandi X-RAY | fresco Summary
Support
Quality
Security
License
Reuse
- Updates the builder based on the attributes of the builder .
- Decodes bitmaps from an input stream .
- Gets an object from the pool .
- Parses next data .
- On mount .
- Produce results from the encoder .
- Submit a request to the controller .
- Fetch network with request .
- Transcodes an encoded image .
- Waits for a data source to complete .
fresco Key Features
fresco Examples and Code Snippets
...
# Enables Flipper.
#
# Note that if you have use_frameworks! enabled, Flipper will not work and
# you should disable these next few lines.
use_flipper!({ 'Flipper' => '0.87' })
post_install do |installer|
flipper_post_install(installer)
find_and_replace("Pods/Headers/Private/RCT-Folly/folly/synchronization/DistributedMutex-inl.h",
"atomic_notify_one(state)", "folly::atomic_notify_one(state)")
find_and_replace("Pods/Flipper-Folly/folly/synchronization/DistributedMutex-inl.h",
"atomic_wait_until(&state, previous | data, deadline)", "folly::atomic_wait_until(&state, previous | data, deadline)")
end
...
if (
event is InputEventScreenDrag
or event is InputEventScreenTouch
or event is InputEventMouse
):
var viewport := get_viewport()
var position:Vector2 = viewport.get_canvas_transform().affine_inverse().xform(event.position)
var objects := get_world_2d().direct_space_state.intersect_point(position)
for object in objects:
print(object.collider)
for i in get_slide_count():
var collision = get_slide_collision(i)
print("Collided with: ", collision.collider.name)
var parameters := Physics2DShapeQueryParameters.new()
parameters.transform = global_transform
parameters.set_shape($CollisionShape2D.shape)
var results = get_world_2d().direct_space_state.intersect_shape(parameters)
for result in results:
print(result.collider)
class_name FauxBody2D
extends Node2D
var _body:RID
var _invalid_rid:RID
func _enter_tree() -> void:
_body = Physics2DServer.body_create()
func _exit_tree() -> void:
Physics2DServer.free_rid(_body)
_body = _invalid_rid
func _enter_tree() -> void:
# …
Physics2DServer.body_set_space(_body, get_world_2d().space)
export var shape:Shape2D setget set_shape
export var disabled:bool setget set_disabled
export var one_way_collision:bool setget set_one_way_collision
export(float, 0.0, 128.0) var one_way_collision_margin:float setget set_one_way_collision_margin
var _shape:RID
func _enter_tree() -> void:
# …
_update_shape()
func _update_shape() -> void:
var new_shape = _invalid_rid if shape == null else shape.get_rid()
if new_shape == _shape:
return
if _shape.get_id() != 0:
Physics2DServer.body_remove_shape(_body, 0)
_shape = new_shape
if _shape.get_id() != 0:
Physics2DServer.body_add_shape(_body, _shape, Transform2D.IDENTITY, disabled)
Physics2DServer.body_set_shape_as_one_way_collision(_body, 0, one_way_collision, one_way_collision_margin)
func set_shape(new_value:Shape2D) -> void:
if shape == new_value:
return
shape = new_value
if _body.get_id() == 0:
return
_update_shape()
func set_disabled(new_value:bool) -> void:
if disabled == new_value:
return
disabled = new_value
if _body.get_id() == 0:
return
if _shape.get_id() != 0:
Physics2DServer.body_set_shape_disabled(_body, 0, disabled)
func set_one_way_collision(new_value:bool) -> void:
if one_way_collision == new_value:
return
one_way_collision = new_value
if _body.get_id() == 0:
return
if _shape.get_id() != 0:
Physics2DServer.body_set_shape_as_one_way_collision(_body, 0, one_way_collision, one_way_collision_margin)
func set_one_way_collision_margin(new_value:float) -> void:
if one_way_collision_margin == new_value:
return
one_way_collision_margin = new_value
if _body.get_id() == 0:
return
if _shape.get_id() != 0:
Physics2DServer.body_set_shape_as_one_way_collision(_body, 0, one_way_collision, one_way_collision_margin)
signal sleeping_state_changed()
export var linear_velocity:Vector2 setget set_linear_velocity
export var angular_velocity:float setget set_angular_velocity
export var can_sleep:bool = true setget set_can_sleep
export var sleeping:bool setget set_sleeping
export var custom_integrator:bool setget set_custom_integrator
func _enter_tree() -> void:
# …
Physics2DServer.body_set_state(_body, Physics2DServer.BODY_STATE_TRANSFORM, global_transform)
Physics2DServer.body_set_state(_body, Physics2DServer.BODY_STATE_ANGULAR_VELOCITY, angular_velocity)
Physics2DServer.body_set_state(_body, Physics2DServer.BODY_STATE_CAN_SLEEP, can_sleep)
Physics2DServer.body_set_state(_body, Physics2DServer.BODY_STATE_LINEAR_VELOCITY, linear_velocity)
Physics2DServer.body_set_state(_body, Physics2DServer.BODY_STATE_SLEEPING, sleeping)
Physics2DServer.body_set_force_integration_callback(_body, self, "_body_moved", 0)
Physics2DServer.body_set_omit_force_integration(_body, custom_integrator)
func _body_moved(state:Physics2DDirectBodyState, _user_data) -> void:
_integrate_forces(state)
global_transform = state.transform
angular_velocity = state.angular_velocity
linear_velocity = state.linear_velocity
if sleeping != state.sleeping:
sleeping = state.sleeping
emit_signal("sleeping_state_changed")
# warning-ignore:unused_argument
func _integrate_forces(state:Physics2DDirectBodyState) -> void:
pass
func set_linear_velocity(new_value:Vector2) -> void:
if linear_velocity == new_value:
return
linear_velocity = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_state(_body, Physics2DServer.BODY_STATE_LINEAR_VELOCITY, linear_velocity)
func set_angular_velocity(new_value:float) -> void:
if angular_velocity == new_value:
return
angular_velocity = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_state(_body, Physics2DServer.BODY_STATE_ANGULAR_VELOCITY, angular_velocity)
func set_can_sleep(new_value:bool) -> void:
if can_sleep == new_value:
return
can_sleep = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_state(_body, Physics2DServer.BODY_STATE_CAN_SLEEP, can_sleep)
func set_sleeping(new_value:bool) -> void:
if sleeping == new_value:
return
sleeping = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_state(_body, Physics2DServer.BODY_STATE_SLEEPING, sleeping)
func set_custom_integrator(new_value:bool) -> void:
if custom_integrator == new_value:
return
custom_integrator = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_omit_force_integration(_body, custom_integrator)
func _enter_tree() -> void:
# …
set_notify_transform(true)
func _notification(what: int) -> void:
if what == NOTIFICATION_TRANSFORM_CHANGED:
if _body.get_id() != 0:
Physics2DServer.body_set_state(_body, Physics2DServer.BODY_STATE_TRANSFORM, global_transform)
export(float, EXP, 0.01, 65535.0) var mass:float = 1.0 setget set_mass
export(float, EXP, 0.0, 65535.0) var inertia:float = 1.0 setget set_inertia
export(float, 0.0, 1.0) var bounce:float = 0.0 setget set_bounce
export(float, 0.0, 1.0) var friction:float = 1.0 setget set_friction
export(float, -128.0, 128.0) var gravity_scale:float = 1.0 setget set_gravity_scale
export(float, -1.0, 100.0) var linear_damp:float = -1 setget set_linear_damp
export(float, -1.0, 100.0) var angular_damp:float = -1 setget set_angular_damp
func _enter_tree() -> void:
# …
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_ANGULAR_DAMP, angular_damp)
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_GRAVITY_SCALE, gravity_scale)
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_INERTIA, inertia)
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_LINEAR_DAMP, linear_damp)
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_MASS, mass)
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_BOUNCE, bounce)
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_FRICTION, friction)
# …
func set_mass(new_value:float) -> void:
if mass == new_value:
return
mass = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_MASS, mass)
func set_inertia(new_value:float) -> void:
if inertia == new_value:
return
inertia = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_INERTIA, inertia)
func set_bounce(new_value:float) -> void:
if bounce == new_value:
return
bounce = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_BOUNCE, bounce)
func set_friction(new_value:float) -> void:
if friction == new_value:
return
friction = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_FRICTION, friction)
func set_gravity_scale(new_value:float) -> void:
if gravity_scale == new_value:
return
gravity_scale = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_GRAVITY_SCALE, gravity_scale)
func set_linear_damp(new_value:float) -> void:
if linear_damp == new_value:
return
linear_damp = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_LINEAR_DAMP, linear_damp)
func set_angular_damp(new_value:float) -> void:
if angular_damp == new_value:
return
angular_damp = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_param(_body, Physics2DServer.BODY_PARAM_ANGULAR_DAMP, angular_damp)
export(int, "Disabled", "Cast Ray", "Cast Shape") var continuous_cd
func _enter_tree() -> void:
# …
Physics2DServer.body_set_continuous_collision_detection_mode(_body, continuous_cd)
# …
func set_continuous_cd(new_value:int) -> void:
if continuous_cd == new_value:
return
continuous_cd = new_value
if _body.get_id() == 0:
return
Physics2DServer.body_set_continuous_collision_detection_mode(_body, continuous_cd)
export var applied_force:Vector2 setget set_applied_force
export var applied_torque:float setget set_applied_torque
export var center_of_mass:Vector2
export var auto_reset_forces:bool
func _enter_tree() -> void:
# …
Physics2DServer.body_add_central_force(_body, applied_force)
Physics2DServer.body_add_torque(_body, applied_torque)
func _body_moved(state:Physics2DDirectBodyState, _user_data) -> void:
# …
if auto_reset_forces:
Physics2DServer.body_add_central_force(_body, -applied_force)
Physics2DServer.body_add_torque(_body, -applied_torque)
applied_force = Vector2.ZERO
applied_torque = 0
func add_central_force(force:Vector2) -> void:
applied_force += force
if _body.get_id() != 0:
Physics2DServer.body_add_central_force(_body, force)
func add_force(force:Vector2, offset:Vector2) -> void:
var torque := (offset - center_of_mass).cross(force)
applied_force += force
applied_torque += torque
if _body.get_id() != 0:
Physics2DServer.body_add_central_force(_body, force)
Physics2DServer.body_add_torque(_body, torque)
func add_torque(torque:float) -> void:
applied_torque += torque
if _body.get_id() != 0:
Physics2DServer.body_add_torque(_body, torque)
func apply_central_impulse(impulse:Vector2) -> void:
if _body.get_id() != 0:
Physics2DServer.body_apply_central_impulse(_body, impulse)
func apply_impulse(offset:Vector2, impulse:Vector2) -> void:
if _body.get_id() != 0:
Physics2DServer.body_apply_impulse(_body, offset, impulse)
func apply_torque_impulse(torque:float) -> void:
if _body.get_id() != 0:
Physics2DServer.body_apply_torque_impulse(_body, torque)
func set_applied_force(new_value:Vector2) -> void:
if applied_force == new_value:
return
if _body.get_id() != 0:
var difference := new_value - applied_force
Physics2DServer.body_add_central_force(_body, difference)
applied_force = new_value
func set_applied_torque(new_value:float) -> void:
if applied_torque == new_value:
return
if _body.get_id() != 0:
var difference := new_value - applied_torque
Physics2DServer.body_add_torque(_body, difference)
applied_torque = new_value
var collision_exceptions:Array
func add_collision_exception_with(body:Node) -> void:
var collision_object := body as PhysicsBody2D
if not is_instance_valid(collision_object):
push_error( "Collision exception only works between two objects of PhysicsBody type.")
return
var rid = collision_object.get_rid()
if rid.get_id() == 0:
return
if collision_exceptions.has(collision_object):
return
collision_exceptions.append(collision_object)
if _body.get_id() != 0:
Physics2DServer.body_add_collision_exception(_body, rid)
func get_collision_exceptions() -> Array:
return collision_exceptions
func remove_collision_exception_with(body:Node) -> void:
var collision_object := body as PhysicsBody2D
if not is_instance_valid(collision_object):
push_error( "Collision exception only works between two objects of PhysicsBody type.")
return
var rid = collision_object.get_rid()
if rid.get_id() == 0:
return
if not collision_exceptions.has(collision_object):
return
collision_exceptions.erase(collision_object)
if _body.get_id() != 0:
Physics2DServer.body_remove_collision_exception(_body, rid)
func test_motion(motion:Vector2, infinite_inertia:bool = true, margin:float = 0.08, result:Physics2DTestMotionResult = null) -> bool:
if _body.get_id() == 0:
push_error("body is not inside the scene tree")
return false
return Physics2DServer.body_test_motion(_body, global_transform, motion, infinite_inertia, margin, result)
func set_axis_velocity(axis_velocity:Vector2) -> void:
Physics2DServer.body_set_axis_velocity(_body, axis_velocity)
func set_axis_velocity(axis_velocity:Vector2) -> void:
self.linear_velocity = axis_velocity + linear_velocity.slide(axis_velocity.normalized())
var _area:RID
func _enter_tree() -> void:
_area = Physics2DServer.area_create()
Physics2DServer.area_set_space(_area, get_world_2d().space)
Physics2DServer.area_set_transform(_area, global_transform)
# …
func _exit_tree() -> void:
Physics2DServer.free_rid(_area)
_area = _invalid_rid
# …
func _update_shape() -> void:
# …
if _shape.get_id() != 0:
Physics2DServer.area_add_shape(_area, _shape, Transform2D.IDENTITY, disabled)
# …
func _notification(what: int) -> void:
if what == NOTIFICATION_TRANSFORM_CHANGED:
# …
if _area.get_id() != 0:
Physics2DServer.area_set_transform(_area, global_transform)
export var lock_rotation:bool setget set_lock_rotation
export var freeze:bool setget set_freeze
export(int, "Static", "Kinematic", "Area") var freeze_mode:int setget set_freeze_mode
func _enter_tree() -> void:
# …
_update_body_mode()
func _update_body_mode() -> void:
if freeze:
if freeze_mode == 1:
Physics2DServer.body_set_mode(_body, Physics2DServer.BODY_MODE_KINEMATIC)
else:
Physics2DServer.body_set_mode(_body, Physics2DServer.BODY_MODE_STATIC)
else:
if lock_rotation:
Physics2DServer.body_set_mode(_body, Physics2DServer.BODY_MODE_CHARACTER)
else:
Physics2DServer.body_set_mode(_body, Physics2DServer.BODY_MODE_RIGID)
func set_lock_rotation(new_value:bool) -> void:
if lock_rotation == new_value:
return
lock_rotation = new_value
if _body.get_id() == 0:
return
_update_body_mode()
func set_freeze(new_value:bool) -> void:
if freeze == new_value:
return
freeze = new_value
if _body.get_id() == 0:
return
_update_body_mode()
func set_freeze_mode(new_value:int) -> void:
if freeze_mode == new_value:
return
freeze_mode = new_value
if _body.get_id() == 0:
return
_update_body_mode()
signal input_event(viewport, event, shape_idx)
signal mouse_entered()
signal mouse_exited()
export var input_pickable:bool setget set_input_pickable
var _mouse_is_inside:bool
func _enter_tree() -> void:
# …
_update_pickable()
# …
func _notification(what: int) -> void:
# …
if what == NOTIFICATION_VISIBILITY_CHANGED:
_update_pickable()
func _update_pickable() -> void:
set_process_input(input_pickable and _body.get_id() != 0 and is_visible_in_tree())
func _input(event: InputEvent) -> void:
if (
not (event is InputEventScreenDrag)
and not (event is InputEventScreenTouch)
and not (event is InputEventMouse)
):
return
var viewport := get_viewport()
var position:Vector2 = viewport.get_canvas_transform().affine_inverse().xform(event.position)
var objects := get_world_2d().direct_space_state.intersect_point(position, 32, [], 0x7FFFFFFF, false, true)
var is_inside := false
for object in objects:
if object.rid == _area:
is_inside = true
break
if is_inside:
_input_event(viewport, event, 0)
emit_signal("input_event", viewport, event, 0)
if event is InputEventMouse and _mouse_is_inside != is_inside:
_mouse_is_inside = is_inside
if _mouse_is_inside:
emit_signal("mouse_entered")
else:
emit_signal("mouse_exited")
# warning-ignore:unused_argument
# warning-ignore:unused_argument
# warning-ignore:unused_argument
func _input_event(viewport:Object, event:InputEvent, shape_idx:int) -> void:
pass
func set_input_pickable(new_value:bool) -> void:
if input_pickable == new_value:
return
input_pickable = new_value
_update_pickable()
signal body_entered(body)
signal body_exited(body)
signal body_shape_entered(body_rid, body, body_shape_index, local_shape_index)
signal body_shape_exited(body_rid, body, body_shape_index, local_shape_index)
signal area_entered(area)
signal area_exited(area)
signal area_shape_entered(area_rid, area, area_shape_index, local_shape_index)
signal area_shape_exited(area_rid, area, area_shape_index, local_shape_index)
export var monitorable:bool setget set_monitorable
export var monitoring:bool setget set_monitoring
var overlapping_body_instances:Dictionary
var overlapping_area_instances:Dictionary
var overlapping_bodies:Dictionary
var overlapping_areas:Dictionary
func _enter_tree() -> void:
# …
_update_monitoring()
# …
func _update_monitoring() -> void:
Physics2DServer.area_set_monitorable(_area, monitorable or monitoring)
if monitoring:
Physics2DServer.area_set_monitor_callback(_area, self, "_body_monitor")
Physics2DServer.area_set_area_monitor_callback(_area, self, "_area_monitor")
else:
Physics2DServer.area_set_monitor_callback(_area, null, "")
Physics2DServer.area_set_area_monitor_callback(_area, null, "")
func _body_monitor(status:int, body:RID, instance_id:int, body_shape_index:int, local_shape_index:int) -> void:
if _body == body:
return
var instance := instance_from_id(instance_id)
if status == 0:
# entered
if not overlapping_bodies.has(body):
overlapping_bodies[body] = 0
overlapping_body_instances[instance] = instance
emit_signal("body_entered", instance)
overlapping_bodies[body] += 1
emit_signal("body_shape_entered", body, instance, body_shape_index, local_shape_index)
else:
# exited
emit_signal("body_shape_exited", body, instance, body_shape_index, local_shape_index)
overlapping_bodies[body] -= 1
if overlapping_bodies[body] == 0:
overlapping_bodies.erase(body)
overlapping_body_instances.erase(instance)
emit_signal("body_exited", instance)
func _area_monitor(status:int, area:RID, instance_id:int, area_shape_index:int, local_shape_index:int) -> void:
var instance := instance_from_id(instance_id)
if status == 0:
# entered
if not overlapping_areas.has(area):
overlapping_areas[area] = 0
overlapping_area_instances[instance] = instance
emit_signal("area_entered", instance)
overlapping_areas[area] += 1
emit_signal("area_shape_entered", area, instance, area_shape_index, local_shape_index)
else:
# exited
emit_signal("area_shape_exited", area, instance, area_shape_index, local_shape_index)
overlapping_areas[area] -= 1
if overlapping_areas[area] == 0:
overlapping_areas.erase(area)
overlapping_area_instances.erase(instance)
emit_signal("area_exited", instance)
func get_overlapping_bodies() -> Array:
if not monitoring:
push_error("monitoring is false")
return []
return overlapping_body_instances.keys()
func get_overlapping_areas() -> Array:
if not monitoring:
push_error("monitoring is false")
return []
return overlapping_area_instances.keys()
func overlaps_body(body:Node) -> bool:
if not monitoring:
return false
return overlapping_body_instances.has(body)
func overlaps_area(area:Node) -> bool:
if not monitoring:
return false
return overlapping_area_instances.has(area)
func set_monitoring(new_value:bool) -> void:
if monitoring == new_value:
return
monitoring = new_value
if _area.get_id() == 0:
return
_update_monitoring()
func set_monitorable(new_value:bool) -> void:
if monitorable == new_value:
return
monitorable = new_value
if _area.get_id() == 0:
return
_update_monitoring()
export(int, LAYERS_2D_PHYSICS) var collision_layer:int = 1 setget set_collision_layer
export(int, LAYERS_2D_PHYSICS) var collision_mask:int = 1 setget set_collision_mask
func _enter_tree() -> void:
# …
_update_collision_layer_and_mask()
# …
func _update_collision_layer_and_mask() -> void:
Physics2DServer.area_set_collision_layer(_area, collision_layer)
Physics2DServer.body_set_collision_layer(_body, collision_layer if not freeze or freeze_mode != 2 else 0)
Physics2DServer.area_set_collision_mask(_area, collision_mask)
Physics2DServer.body_set_collision_mask(_body, collision_mask if not freeze or freeze_mode != 2 else 0)
func set_collision_layer(new_value:int) -> void:
if collision_layer == new_value:
return
collision_layer = new_value
if _body.get_id() == 0:
return
_update_collision_layer_and_mask()
func set_collision_mask(new_value:int) -> void:
if collision_mask == new_value:
return
collision_mask = new_value
if _body.get_id() == 0:
return
_update_collision_layer_and_mask()
func get_collision_layer_bit(bit:int) -> bool:
if bit < 0 or bit > 31:
push_error("Collision layer bit must be between 0 and 31 inclusive.")
return false
return collision_layer & (1 << bit) != 0
func get_collision_mask_bit(bit:int) -> bool:
if bit < 0 or bit > 31:
push_error("Collision mask bit must be between 0 and 31 inclusive.")
return false
return collision_mask & (1 << bit) != 0
func set_collision_layer_bit(bit:int, value:bool) -> void:
if bit < 0 or bit > 31:
push_error("Collision layer bit must be between 0 and 31 inclusive.")
return
if value:
self.collision_layer = collision_layer | 1 << bit
else:
self.collision_layer = collision_layer & ~(1 << bit)
func set_collision_mask_bit(bit:int, value:bool) -> void:
if bit < 0 or bit > 31:
push_error("Collision mask bit must be between 0 and 31 inclusive.")
return
if value:
self.collision_mask = collision_mask | 1 << bit
else:
self.collision_mask = collision_mask & ~(1 << bit)
func _update_body_mode() -> void:
_update_collision_layer_and_mask()
# …
const cors = require("cors");
let whitelist = ["http://localhost:3000"];
// Middleware
app.use(
cors({
origin: function (origin, callback) {
if (!origin) return callback(null, true);
if (whitelist.indexOf(origin) === -1) {
var message =
"The CORS policy for this origin doesnt " +
"allow access from the particular origin.";
return callback(new Error(message), false);
}
return callback(null, true);
},
})
);
class TickingScrollPane extends ScrollPane {
//Our special event type, to be fired after a delay when scrolling stops
public static final EventType SCROLL_TICK = new EventType<>(TickingScrollPane.class.getName() + ".SCROLL_TICK");
// Strong refs to listener and timeline
private final ChangeListener scrollListener; //Will register any scrolling
private final Timeline notifyLoop; //Will check every 100ms how long ago we last scrolled
// Last registered scroll timing
private long lastScroll = 0; // 0 means "no scroll registered"
public TickingScrollPane() {
super();
/* Register any time a scrollbar moves (scrolling by any means or resizing)
* /!\ will fire once when initially shown because of width/height listener */
scrollListener = (_observable, _oldValue, _newValue) -> {
lastScroll = System.currentTimeMillis();
};
this.vvalueProperty().addListener(scrollListener);
this.hvalueProperty().addListener(scrollListener);
this.widthProperty().addListener(scrollListener);
this.heightProperty().addListener(scrollListener);
//ScrollEvent.SCROLL works only for mouse wheel, but you could as well use it
/* Every 100ms, check if there's a registered scroll.
* If so, and it's older than 1000ms, then fire and unregister it.
* Will therefore fire at most once per second, about 1 second after scroll stopped */
this.notifyLoop = new Timeline(new KeyFrame(Duration.millis(100), //100ms exec. interval
e -> {
if (lastScroll == 0)
return;
long now = System.currentTimeMillis();
if (now - lastScroll > 1000) { //1000ms delay
lastScroll = 0;
fireEvent(new Event(this, this, SCROLL_TICK));
}
}));
this.notifyLoop.setCycleCount(Timeline.INDEFINITE);
this.notifyLoop.play();
}
}
package application;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.event.Event;
import javafx.event.EventType;
import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
class TickingScrollPane extends ScrollPane {
//Our special event type, to be fired after a delay when scrolling stops
public static final EventType SCROLL_TICK = new EventType<>(TickingScrollPane.class.getName() + ".SCROLL_TICK");
// Strong refs to listener and timeline
private final ChangeListener scrollListener; //Will register any scrolling
private final Timeline notifyLoop; //Will check every 100ms how long ago we last scrolled
// Last registered scroll timing
private long lastScroll = 0; // 0 means "no scroll registered"
public TickingScrollPane() {
super();
/* Register any time a scrollbar moves (scrolling by any means or resizing)
* /!\ will fire once when initially shown because of width/height listener */
scrollListener = (_observable, _oldValue, _newValue) -> {
lastScroll = System.currentTimeMillis();
};
this.vvalueProperty().addListener(scrollListener);
this.hvalueProperty().addListener(scrollListener);
this.widthProperty().addListener(scrollListener);
this.heightProperty().addListener(scrollListener);
//ScrollEvent.SCROLL works only for mouse wheel, but you could as well use it
/* Every 100ms, check if there's a registered scroll.
* If so, and it's older than 1000ms, then fire and unregister it.
* Will therefore fire at most once per second, about 1 second after scroll stopped */
this.notifyLoop = new Timeline(new KeyFrame(Duration.millis(100), //100ms exec. interval
e -> {
if (lastScroll == 0)
return;
long now = System.currentTimeMillis();
if (now - lastScroll > 1000) { //1000ms delay
lastScroll = 0;
fireEvent(new Event(this, this, SCROLL_TICK));
}
}));
this.notifyLoop.setCycleCount(Timeline.INDEFINITE);
this.notifyLoop.play();
}
}
public class TickingScrollPaneTest extends Application {
@Override
public void start(Stage primaryStage) {
try {
//Draw our scrollpane, add a bunch of rectangles in a VBox to fill its contents
TickingScrollPane root = new TickingScrollPane();
root.setPadding(new Insets(5));
VBox vb = new VBox(6);
root.setContent(vb);
final int rectsCount = 10;
for (int i = 0; i < rectsCount; i++) {
Rectangle r = new Rectangle(Math.random() * 900, 60); //Random width, 60px height
r.setFill(Color.hsb(360. / rectsCount * i, 1, .85)); //Changing hue (rainbow style)
vb.getChildren().add(r);
}
//Log every scroll tick to console
root.addEventHandler(TickingScrollPane.SCROLL_TICK, e -> {
System.out.println(String.format(
"%s:\tScrolled 1s ago to (%s)",
LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME),
getViewableBounds(root)
));
});
//Show in a 400x400 window
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.setTitle("TickingScrollPane test");
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Calculate viewable bounds for contents for ScrollPane
* given viewport size and scroll position
*/
private static Bounds getViewableBounds(ScrollPane scrollPane) {
Bounds vbds = scrollPane.getViewportBounds();
Bounds cbds = scrollPane.getContent().getLayoutBounds();
double hoffset = 0;
if (cbds.getWidth() > vbds.getWidth())
hoffset = Math.max(0, cbds.getWidth() - vbds.getWidth()) * (scrollPane.getHvalue() - scrollPane.getHmin()) / (scrollPane.getHmax() - scrollPane.getHmin());
double voffset = 0;
if (cbds.getHeight() > vbds.getHeight())
voffset = Math.max(0, cbds.getHeight() - vbds.getHeight()) * (scrollPane.getVvalue() - scrollPane.getVmin()) / (scrollPane.getVmax() - scrollPane.getVmin());
Bounds viewBounds = new BoundingBox(hoffset, voffset, vbds.getWidth(), vbds.getHeight());
return viewBounds;
}
public static void main(String[] args) {
launch(args);
}
}
import {NextResponse} from 'next/server';
const Middleware = (req) => {
const {pathname} = req.nextUrl;
if (pathname.includes('/%')) {
return NextResponse.rewrite(`/statics/${pathname.slice(pathname.indexOf('%'))}`);
}
if (pathname === pathname.toLowerCase()) {
return NextResponse.next();
}
return NextResponse.redirect(`${req.nextUrl.origin}${pathname.toLowerCase()}`);
};
export default Middleware;
import { NextResponse } from 'next/server';
export function middleware(req) {
const url = req.nextUrl.clone();
if (url.pathname === url.pathname.toLowerCase()) {
return NextResponse.next();
}
if (url.pathname.includes('/%')) {
url.pathname = '/statics/' +
url.pathname.slice(url.pathname.indexOf('%'));
return NextResponse.rewrite(url);
}
return NextResponse.next();
}
exports.showAllUnreadPosts = (req, res, next) => {
db.Post.findAll({
where: {
'$readposts.UserId$': res.locals.userId // User Id extracted from auth middleware
},
attributes: ['id'],
include: [{
model: db.ReadPost,
required: false,
attributes: [],
}]
}).then(readPosts => {
db.Post.findAll({
where: {
id: {
[Op.not]: (() => readPosts.map(readPost => readPost.id))()
}
}
})
.then((unreadPosts) => {
res.status(200).json(unreadPosts);
})
.catch((error) => {
res.status(500).json({
error: 'Error' + error
})
})
})
.catch((error) => {
res.status(500).json({
error: 'Error ' + error
})
})
}
class AddRecordTableView(QtWidgets.QTableView):
def addRecordAndEdit(self):
self.setCurrentIndex(QtCore.QModelIndex())
row = self.model().rowCount()
self.model().insertRow(row)
firstColumn = self.horizontalHeader().logicalIndex(0)
index = self.model().index(row, firstColumn)
self.setCurrentIndex(index)
if index.flags() & QtCore.Qt.ItemIsEditable:
self.edit(index)
# we assume that the new index is always the last row, so we
# scroll to the bottom no matter what; if we implement a "fake
# item" to add new records, this will ensure that it will always
# be visible when editing begins
QtCore.QTimer.singleShot(0, lambda:
self.verticalScrollBar().setValue(
self.verticalScrollBar().maximum()))
class AddRecordTableView(QtWidgets.QTableView):
def addRecordAndEdit(self):
# as above...
def _lastColumn(self):
if not self.model():
return -1
return self.horizontalHeader().logicalIndex(
self.model().columnCount()
- self.horizontalHeader().hiddenSectionCount() - 1)
def _lastRow(self):
if not self.model():
return -1
return self.verticalHeader().logicalIndex(
self.model().rowCount()
- self.verticalHeader().hiddenSectionCount() - 1)
def closeEditor(self, editor, hint):
if hint == QtWidgets.QAbstractItemDelegate.EditNextItem:
current = self.currentIndex()
if (current.row() == self._lastRow() and
current.column() == self._lastColumn()):
super().closeEditor(
editor, QtWidgets.QAbstractItemDelegate.NoHint)
QtCore.QTimer.singleShot(0, self.addRecordAndEdit)
return
super().closeEditor(editor, hint)
def canAddRowFromEventAtPos(self, pos):
# we will need this later...
lastColumn = self._lastColumn()
if lastColumn < 0:
# this should not happen...
return False
lastRow = self._lastRow()
rect = self.visualRect(self.model().index(lastRow, lastColumn))
return rect.isNull() or pos.y() >= rect.bottom()
def mouseDoubleClickEvent(self, event):
super().mouseDoubleClickEvent(event)
if (event.button() != QtCore.Qt.LeftButton or
self.indexAt(event.pos()).isValid()):
return
if self.canAddRowFromEventAtPos(event.pos()):
self.addRecordAndEdit()
class AddRecordTableViewFakeItem(AddRecordTableView):
_addRect = None
_hoverAdd = False
def canAddRowFromEventAtPos(self, pos):
# override for AddRecordTableView, we can only add new records as long
# as the event pos is within the "add rect" boundaries
return self._lastColumn() >= 0 and pos in self.addRect()
def updateGeometries(self):
super().updateGeometries()
self._addRect = None
# increase the maximum value of the vertical scroll bar in order to allow
# scrolling *beyond* the last row
viewHeight = self.viewport().size().height()
vlength = self.verticalHeader().length()
sectionSize = self.verticalHeader().defaultSectionSize()
if (self.verticalScrollMode() == self.ScrollPerItem and
viewHeight < vlength + sectionSize):
extend = 1
elif viewHeight < vlength + sectionSize:
extend = min(sectionSize, vlength + sectionSize - viewHeight)
else:
# the viewport is tall enough, ignore
return
self.verticalScrollBar().setMaximum(
self.verticalScrollBar().maximum() + extend)
def scrollContentsBy(self, dx, dy):
super().scrollContentsBy(dx, dy)
if dy:
self._addRect = None
if (self.verticalScrollMode() == self.ScrollPerItem and
0 < self.verticalScrollBar().value() == self.verticalScrollBar().maximum()):
self.verticalHeader().setOffset(
self.verticalHeader().offset()
+ self.verticalHeader().defaultSectionSize())
self.viewport().scroll(0, -self.verticalHeader().defaultSectionSize())
def viewportEvent(self, event):
if event.type() in (event.HoverEnter, event.HoverMove, event.HoverLeave):
addRect = self.addRect()
hoverAdd = event.pos() in addRect
if self._hoverAdd != hoverAdd:
self._hoverAdd = hoverAdd
self.viewport().update(addRect)
return super().viewportEvent(event)
def addRect(self):
if self._addRect is None:
lastRow = self._lastRow()
if lastRow < 0:
y = 0
else:
vr = self.visualRect(self.model().index(lastRow, 0))
y = vr.y() + vr.height()
if self.horizontalScrollBar().value() < self.horizontalScrollBar().maximum():
width = self.viewport().width() - 1
else:
lastColumn = self._lastColumn()
right = (self.horizontalHeader().sectionPosition(lastColumn)
+ self.horizontalHeader().sectionSize(lastColumn))
width = right - self.horizontalHeader().offset() - 1
self._addRect = QtCore.QRect(0, y, width,
self.verticalHeader().defaultSectionSize() - 1)
return self._addRect
def enterEvent(self, event):
super().enterEvent(event)
self.viewport().update()
def leaveEvent(self, event):
super().leaveEvent(event)
self.viewport().update()
def paintEvent(self, event):
super().paintEvent(event)
model = self.model()
if not model or not self.underMouse():
return
r = self.addRect()
if r.y() > event.rect().bottom():
return
qp = QtGui.QPainter(self.viewport())
qp.setRenderHint(qp.Antialiasing)
qp.translate(.5, .5)
if not self._hoverAdd:
color = self.palette().color(QtGui.QPalette.Disabled, QtGui.QPalette.Text)
else:
color = self.palette().color(QtGui.QPalette.Text)
color.setAlphaF(color.alphaF() * .75)
qp.setPen(color)
qp.setBrush(QtCore.Qt.NoBrush)
qp.drawRoundedRect(r.adjusted(1, 1, -1, -1), 2, 2)
fm = self.fontMetrics()
text = fm.elidedText('Double click here to add record', QtCore.Qt.ElideRight,
r.width() - 4 - fm.horizontalAdvance(' ') * 2)
qp.drawText(r, QtCore.Qt.AlignCenter, text)
Trending Discussions on fresco
Trending Discussions on fresco
QUESTION
dependencies {
implementation "com.google.android.gms:play-services-base:16.1.0"
implementation "com.google.firbase:firebase-core:17.0.1"
implementation "com.google.firebase:firebase-messaging:19.0.1"
// implementation platform('com.google.firebase:firebase-bom:29.2.0')
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
want to connect firebase cloud messaging and i got the error Could not find com.google.firbase:firebase-core:17.0.1. when i run the android app.
ANSWER
Answered 2022-Mar-17 at 05:30I think that you forgot the letter e
for firbase
. Replace "com.google.firbase:firebase-core:17.0.1" with "com.google.firebase:firebase-core:17.0.1".
I believe that the firebase-core
has been removed in React Native Firebase, see about the installation of Cloud Messaging on documentation, it doesn't need the firebase-core
and firebase-messaging
.
QUESTION
I have a react-native project. After the bitnary (jcenter)
shutted down I started to replace it. Currently I'm using mavenCentral()
. Also I'm using the react-native-intercom (wrapper for intercom)
. When I'm trying to build gradlew assembleRelease
. Its throws me an error.
Could not determine the dependencies of task ':app:compileReleaseJavaWithJavac'.
> Could not resolve all task dependencies for configuration ':app:releaseCompileClasspath'.
> Could not find com.google.android:flexbox:1.0.0.
Required by:
project :app > io.intercom.android:intercom-sdk-base:5.5.1
I saw the solution, but it didn't help. this one
My files: (if you need more information let me know <3)
build.gradle(app):
apply plugin: "com.android.application"
import com.android.build.OutputFile
import com.sun.org.apache.xalan.internal.xsltc.compiler.Copy
instead
project.ext.react = [
entryFile: "index.js",
enableHermes: false, // clean and rebuild if changing
bundleInBeta: true,
bundleInStaging: true,
devDisabledInBeta: true,
devDisabledInStaging: true,
extraPackagerArgs: ["--max-workers=1"]
]
apply from: "../../node_modules/react-native/react.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false
def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false);
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildToolsVersion '29.0.2'
defaultConfig {
applicationId "se.welcomeapp.android"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 5955
versionName "5.9.55"
multiDexEnabled true
vectorDrawables.useSupportLibrary = true
missingDimensionStrategy 'react-native-camera', 'general'
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
release {
storeFile file("welcome_keystore.jks")
storePassword "DjU@y!@6C^qYqYaGyQCo"
keyAlias "live"
keyPassword "mX7!&@RZiD2^5ZaWkKAV"
}
}
buildTypes {
debug {
applicationIdSuffix ".debug"
manifestPlaceholders = [isDebug:true]
}
beta {
manifestPlaceholders = [isDebug:false]
applicationIdSuffix ".beta"
matchingFallbacks = [ 'release']
signingConfig signingConfigs.release
}
staging {
manifestPlaceholders = [isDebug:false]
applicationIdSuffix ".staging"
matchingFallbacks = [ 'release']
signingConfig signingConfigs.release
}
release {
manifestPlaceholders = [isDebug:false]
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
signingConfig signingConfigs.release
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
dexOptions {
preDexLibraries false
javaMaxHeapSize "3g"
}
packagingOptions {
pickFirst '**/libjsc.so'
pickFirst '**/libc++_shared.so'
pickFirst '**/armeabi-v7a/libc++_shared.so'
pickFirst '**/x86/libc++_shared.so'
pickFirst '**/arm64-v8a/libc++_shared.so'
pickFirst '**/x86_64/libc++_shared.so'
pickFirst '**/x86/libjsc.so'
pickFirst '**/armeabi-v7a/libjsc.so'
}
}
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.28.1'
}
}
apply plugin: 'io.fabric'
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
implementation "com.facebook.react:react-native:+"
implementation project(':react-native-amplitude-analytics')
implementation project(':react-native-color-matrix-image-filters')
implementation project(':react-native-pdf')
implementation project(':rn-fetch-blob')
implementation project(':react-native-document-picker')
implementation project(':react-native-sound')
implementation project(':react-native-audio')
implementation project(':react-native-branch')
implementation "org.webkit:android-jsc:r241213"
implementation project(':@react-native-community_async-storage')
implementation project(':react-native-svg')
implementation project(':react-native-webview')
implementation project(':@react-native-community_netinfo')
implementation project(':react-native-keychain')
implementation project(':react-native-share')
implementation project(':react-native-intercom')
implementation(project(':react-native-firebase')) {
transitive = false
}
implementation(project(':react-native-maps')){
exclude group: 'com.google.android.gms', module: 'play-services-base'
exclude group: 'com.google.android.gms', module: 'play-services-maps'
}
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation(project(':react-native-geolocation-service')) {
exclude group: 'com.google.android.gms', module: 'play-services-location'
}
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation project(':react-native-image-crop-picker')
implementation project(':react-native-fs')
implementation project(':react-native-open-settings')
implementation project(':react-native-linear-gradient')
implementation project(':bugsnag-react-native')
implementation project(':react-native-device-info')
implementation project(':react-native-push-notification')
implementation project(':react-native-geocoder')
implementation project(':react-native-vector-icons')
implementation project(':react-native-i18n')
implementation project(':react-native-fbsdk')
implementation project(':react-native-camera')
provided fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation "com.android.support:appcompat-v7:28.0.0"
implementation "com.android.support:design:28.0.0"
implementation("com.facebook.react:react-native:0.60.4") {
// enforce version to fix https://github.com/facebook/react-native/issues/19259
// if someone send a version of react-native to jcenter, it will use the one
// from jcenter first before node_modules
force = true
}
if (enableHermes) {
def hermesPath = "../../node_modules/hermesvm/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
implementation 'io.github.inflationx:calligraphy3:3.1.1'
implementation 'io.github.inflationx:viewpump:2.0.3'
implementation('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
transitive = true;
}
// Firebase dependencies
implementation "com.google.android.gms:play-services-base:17.0.0"
implementation "com.google.firebase:firebase-core:17.0.1"
implementation "com.google.firebase:firebase-messaging:20.2.4"
implementation "com.google.firebase:firebase-analytics:17.0.1"
// Intercom with Firebase dependencies
implementation 'io.intercom.android:intercom-sdk-base:5.5.1'
implementation 'io.intercom.android:intercom-sdk-fcm:5.+'
// If your app supports Android versions before Ice Cream Sandwich (API level 14)
// TODO: upgrade these to 1.3.0 and test if it solves the crash on samsung for animated gifs
implementation 'com.facebook.fresco:animated-base-support:1.0.1' // For animated GIF support
implementation 'com.facebook.fresco:animated-webp:1.0.1'
implementation 'com.facebook.fresco:animated-gif:1.0.1'
implementation 'com.facebook.fresco:webpsupport:1.0.1'
implementation 'com.android.support:multidex:1.0.3'
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
task wrapper(type: Wrapper) {
gradleVersion = '5.4.1'
}
apply plugin: 'com.google.gms.google-services'
build.gradle (android):
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "29.0.2"
minSdkVersion = 16
compileSdkVersion = 29
targetSdkVersion = 29
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
classpath 'com.google.gms:google-services:4.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
maven { url "$rootDir/../node_modules/react-native/android" }
// maven { url 'https://maven.google.com' }
maven {
url "https://jitpack.io"
credentials { username authToken }
}
maven { url "$rootDir/../node_modules/jsc-android/dist" }
}
}
subprojects {
afterEvaluate {project ->
if (project.hasProperty("android")) {
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
}
}
}
project.configurations.all {
resolutionStrategy {
eachDependency { details ->
if (requested.group == 'com.android.support') {
if (requested.name.startsWith("support-v4")) {
details.useVersion '29.0.0'
}
}
}
}
}
}
ANSWER
Answered 2022-Jan-23 at 12:38I solved it. If you are using the react-native-intercom wrapper. You need to update it, after update everything works fine
QUESTION
This is my Modal component:
export default function LoadingModal(props) {
const {visible} = props;
return (
);
}
Everything is working except the GIF is not animated.
I follow React native components for RN 0.65 and add
// For animated GIF support
implementation 'com.facebook.fresco:fresco:2.0.0'
implementation 'com.facebook.fresco:animated-gif:2.0.0'
into android/app/build.gradle at dependencies
section but it's still not working,
cd android
./gradlew clean
cd ..
react-native run-android ( yarn android )
is not working, too.
I have no idea about it. So I wish that anyone can help me with this problem. Thanks so much.
ANSWER
Answered 2022-Feb-17 at 01:47I fixed
Just use implementation 'com.facebook.fresco:animated-gif:2.5.0'
QUESTION
I am using kotlin ,and I get these error when I add the third library: ** implementation 'com.github.AsynctaskCoffee:tinderlikecardstack:1.0'**
from: https://github.com/AsynctaskCoffee/TinderLikeCardStack
The Error:
Execution failed for task ':app:checkDebugAarMetadata'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
> Could not find com.github.AsynctaskCoffee:tinderlikecardstack:1.0.
Searched in the following locations:
- https://dl.google.com/dl/android/maven2/com/github/AsynctaskCoffee/tinderlikecardstack/1.0/tinderlikecardstack-1.0.pom
- https://repo.maven.apache.org/maven2/com/github/AsynctaskCoffee/tinderlikecardstack/1.0/tinderlikecardstack-1.0.pom
- https://jcenter.bintray.com/com/github/AsynctaskCoffee/tinderlikecardstack/1.0/tinderlikecardstack-1.0.pom
Required by:
project :app
Possible solution:
- Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html
And my guild.gradle(:app)
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-android-extensions'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.gearsrun.stackviewapplication"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation("androidx.recyclerview:recyclerview:1.2.1")
// For control over item selection of both touch and mouse driven selection
implementation("androidx.recyclerview:recyclerview-selection:1.1.0")
implementation 'com.airbnb.android:lottie:3.4.1'
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation 'com.makeramen:roundedimageview:2.3.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.facebook.fresco:fresco:2.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
implementation 'com.github.AsynctaskCoffee:tinderlikecardstack:1.0'
}
build.grandle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.5.0"
repositories {
google()
mavenCentral()
maven { url 'https://jitpack.io' }
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
my gradle.properties:
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
android.enableJetifier=true
Could anyone take a look what was going on please ,thank you so much !
ANSWER
Answered 2022-Feb-12 at 06:48allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.AsynctaskCoffee:TinderLikeCardStack:1.0'
}
Normally, your declarations are true but you may declare them on wrong places. implementation part should be in Gradle app - maven declaration should be in main Gradle.
You can also define project with maven
com.github.AsynctaskCoffee
TinderLikeCardStack
1.0
jitpack.io
https://jitpack.io
Also please check you should disable offline Gradle build. You can also download project and import as module.
QUESTION
i don't know much about java, just started, so i will have difficulties understanding the answers. emli5.
screenshot:
expected output:
in the recyclerview (right), these items are not aligning up like i want them to.
I want that each cell has a fixed size, and maximum number of columns possible in the grid. spacing b/w each cell (both vertical and horizontal) is equal to (left space) divided by (number of columns minus one). [with no extra space left at start, top, bottom or end]
here is the code:
package com.MyStickersWA.DogeStickers;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
@SuppressWarnings("ALL")
public class StickerPackDetailsActivity extends AddStickerPackActivity {
/**
* Do not change below values of below 3 lines as this is also used by WhatsApp
*/
public static final String EXTRA_STICKER_PACK_ID = "sticker_pack_id";
public static final String EXTRA_STICKER_PACK_AUTHORITY = "sticker_pack_authority";
public static final String EXTRA_STICKER_PACK_NAME = "sticker_pack_name";
public static final String EXTRA_STICKER_PACK_WEBSITE = "sticker_pack_website";
public static final String EXTRA_STICKER_PACK_EMAIL = "sticker_pack_email";
public static final String EXTRA_STICKER_PACK_PRIVACY_POLICY = "sticker_pack_privacy_policy";
public static final String EXTRA_STICKER_PACK_LICENSE_AGREEMENT = "sticker_pack_license_agreement";
public static final String EXTRA_STICKER_PACK_TRAY_ICON = "sticker_pack_tray_icon";
public static final String EXTRA_SHOW_UP_BUTTON = "show_up_button";
public static final String EXTRA_STICKER_PACK_DATA = "sticker_pack";
private RecyclerView recyclerView;
private GridLayoutManager layoutManager;
private StickerPreviewAdapter stickerPreviewAdapter;
private int numColumns;
private View addButton;
private View infoButton;
private View backButton;
private View alreadyAdded;
private StickerPack stickerPack;
private WhiteListCheckAsyncTask whiteListCheckAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sticker_pack_details);
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
MobileAds.initialize(this, initializationStatus -> { });
mAdView.loadAd(adRequest);
boolean showUpButton = getIntent().getBooleanExtra(EXTRA_SHOW_UP_BUTTON, false);
stickerPack = getIntent().getParcelableExtra(EXTRA_STICKER_PACK_DATA);
TextView packNameTextView = findViewById(R.id.pack_name);
TextView packPublisherTextView = findViewById(R.id.author);
ImageView packTrayIcon = findViewById(R.id.tray_image);
TextView packSizeTextView = findViewById(R.id.pack_size);
TextView stickersQtyTextView = findViewById(R.id.stickers_qty);
TextView stickersAnimatedView = findViewById(R.id.stickers_animated);
ImageView stickersAnimatedImage = findViewById(R.id.sticker_pack_animation_indicator);
SimpleDraweeView expandedStickerView = findViewById(R.id.sticker_details_expanded_sticker);
addButton = findViewById(R.id.add_to_whatsapp_button);
infoButton = findViewById(R.id.action_info);
backButton = findViewById(R.id.action_back);
alreadyAdded = findViewById(R.id.already_added_button);
layoutManager = new GridLayoutManager(this, 1);
recyclerView = findViewById(R.id.sticker_list);
recyclerView.setLayoutManager(layoutManager);
recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(pageLayoutListener);
if (stickerPreviewAdapter == null) {
stickerPreviewAdapter = new StickerPreviewAdapter(getLayoutInflater(), R.drawable.sticker_error, getResources().getDimensionPixelSize(R.dimen.sticker_pack_details_image_size), getResources().getDimensionPixelSize(R.dimen.sticker_pack_details_image_padding), stickerPack, expandedStickerView);
recyclerView.setAdapter(stickerPreviewAdapter);
}
packNameTextView.setText(stickerPack.name);
packPublisherTextView.setText(stickerPack.publisher);
packTrayIcon.setImageURI(StickerPackLoader.getStickerAssetUri(stickerPack.identifier, stickerPack.trayImageFile));
packSizeTextView.setText(Formatter.formatShortFileSize(this, stickerPack.getTotalSize()));
stickersQtyTextView.setText(stickerPack.getTotalQty() + "");
addButton.setOnClickListener(v -> addStickerPackToWhatsApp(stickerPack.identifier, stickerPack.name));
infoButton.setOnClickListener(v -> onOptionsItemSelected());
backButton.setOnClickListener(v -> finish());
if (stickerPack.animatedStickerPack) {
Uri animatedIcon = Uri.parse("android.resource://" + getPackageName() + "/"+R.drawable.animated_indicator_vector);
stickersAnimatedImage.setImageURI(animatedIcon);
stickersAnimatedView.setText("Animated");
} else {
Uri animatedIcon = Uri.parse("android.resource://" + getPackageName() + "/"+R.drawable.static_indicator_vector);
stickersAnimatedImage.setImageURI(animatedIcon);
stickersAnimatedView.setText("Static");
}
}
private void launchInfoActivity(String publisherWebsite, String publisherEmail, String privacyPolicyWebsite, String licenseAgreementWebsite, String trayIconUriString) {
Intent intent = new Intent(StickerPackDetailsActivity.this, StickerPackInfoActivity.class);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_ID, stickerPack.identifier);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_WEBSITE, publisherWebsite);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_EMAIL, publisherEmail);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_PRIVACY_POLICY, privacyPolicyWebsite);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_LICENSE_AGREEMENT, licenseAgreementWebsite);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_TRAY_ICON, trayIconUriString);
startActivity(intent);
}
public boolean onOptionsItemSelected() {
if (stickerPack != null) {
Uri trayIconUri = StickerPackLoader.getStickerAssetUri(stickerPack.identifier, stickerPack.trayImageFile);
launchInfoActivity(stickerPack.publisherWebsite, stickerPack.publisherEmail, stickerPack.privacyPolicyWebsite, stickerPack.licenseAgreementWebsite, trayIconUri.toString());
return true;
}
return false;
}
private final ViewTreeObserver.OnGlobalLayoutListener pageLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int imgSize = recyclerView.getContext().getResources().getDimensionPixelSize(R.dimen.sticker_pack_details_image_size);
int recyclerViewWidth = recyclerView.getWidth();
int numColumns = recyclerViewWidth / imgSize;
int colSpacing = (recyclerViewWidth - (numColumns * imgSize)) / (numColumns - 1);
// int colSpacing = recyclerView.getWidth() - imgSize * numColumns;
setNumColumns(numColumns, colSpacing);
}
};
@SuppressLint("NotifyDataSetChanged")
private void setNumColumns(int numColumns, int colSpacing) {
if (this.numColumns != numColumns) {
// recyclerView.addItemDecoration(new GridSpacingItemDecoration(4, 2, 2));
layoutManager.setSpanCount(numColumns);
recyclerView.setLayoutManager(layoutManager);
this.numColumns = numColumns;
if (stickerPreviewAdapter != null) {
stickerPreviewAdapter.notifyDataSetChanged();
}
}
}
@Override
protected void onResume() {
super.onResume();
whiteListCheckAsyncTask = new WhiteListCheckAsyncTask(this);
whiteListCheckAsyncTask.execute(stickerPack);
}
@Override
protected void onPause() {
super.onPause();
if (whiteListCheckAsyncTask != null && !whiteListCheckAsyncTask.isCancelled()) {
whiteListCheckAsyncTask.cancel(true);
}
}
private void updateAddUI(Boolean isWhitelisted) {
if (isWhitelisted) {
addButton.setVisibility(View.GONE);
alreadyAdded.setVisibility(View.VISIBLE);
} else {
addButton.setVisibility(View.VISIBLE);
alreadyAdded.setVisibility(View.GONE);
}
}
static class WhiteListCheckAsyncTask extends AsyncTask {
private final WeakReference stickerPackDetailsActivityWeakReference;
WhiteListCheckAsyncTask(StickerPackDetailsActivity stickerPackListActivity) {
this.stickerPackDetailsActivityWeakReference = new WeakReference<>(stickerPackListActivity);
}
@Override
protected final Boolean doInBackground(StickerPack... stickerPacks) {
StickerPack stickerPack = stickerPacks[0];
final StickerPackDetailsActivity stickerPackDetailsActivity = stickerPackDetailsActivityWeakReference.get();
if (stickerPackDetailsActivity == null) {
return false;
}
return WhitelistCheck.isWhitelisted(stickerPackDetailsActivity, stickerPack.identifier);
}
@Override
protected void onPostExecute(Boolean isWhitelisted) {
final StickerPackDetailsActivity stickerPackDetailsActivity = stickerPackDetailsActivityWeakReference.get();
if (stickerPackDetailsActivity != null) {
stickerPackDetailsActivity.updateAddUI(isWhitelisted);
}
}
}
}
/*
* Copyright (c) WhatsApp Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.MyStickersWA.DogeStickers;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
public class StickerPreviewAdapter extends RecyclerView.Adapter {
private static final float COLLAPSED_STICKER_PREVIEW_BACKGROUND_ALPHA = 1f;
private static final float EXPANDED_STICKER_PREVIEW_BACKGROUND_ALPHA = 0.2f;
@NonNull
private final StickerPack stickerPack;
private final int cellSize;
private final int cellLimit;
private final int cellPadding;
private final int errorResource;
private final SimpleDraweeView expandedStickerPreview;
private final LayoutInflater layoutInflater;
private RecyclerView recyclerView;
private View clickedStickerPreview;
float expandedViewLeftX;
float expandedViewTopY;
StickerPreviewAdapter(
@NonNull final LayoutInflater layoutInflater,
final int errorResource,
final int cellSize,
final int cellPadding,
@NonNull final StickerPack stickerPack,
final SimpleDraweeView expandedStickerView) {
this.cellSize = cellSize;
this.cellPadding = cellPadding;
this.cellLimit = 0;
this.layoutInflater = layoutInflater;
this.errorResource = errorResource;
this.stickerPack = stickerPack;
this.expandedStickerPreview = expandedStickerView;
}
@NonNull
@Override
public StickerPreviewViewHolder onCreateViewHolder(@NonNull final ViewGroup viewGroup, final int i) {
View itemView = layoutInflater.inflate(R.layout.sticker_image_item, viewGroup, false);
StickerPreviewViewHolder vh = new StickerPreviewViewHolder(itemView);
ViewGroup.LayoutParams layoutParams = vh.stickerPreviewView.getLayoutParams();
layoutParams.height = cellSize;
layoutParams.width = cellSize;
vh.stickerPreviewView.setLayoutParams(layoutParams);
vh.stickerPreviewView.setPadding(cellPadding, cellPadding, cellPadding, cellPadding);
return vh;
}
@Override
public void onBindViewHolder(@NonNull final StickerPreviewViewHolder stickerPreviewViewHolder, final int i) {
stickerPreviewViewHolder.stickerPreviewView.setImageResource(errorResource);
stickerPreviewViewHolder.stickerPreviewView.setImageURI(StickerPackLoader.getStickerAssetUri(stickerPack.identifier, stickerPack.getStickers().get(i).imageFileName));
stickerPreviewViewHolder.stickerPreviewView.setOnClickListener(v -> expandPreview(i, stickerPreviewViewHolder.stickerPreviewView));
}
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
this.recyclerView = recyclerView;
recyclerView.addOnScrollListener(hideExpandedViewScrollListener);
}
@Override
public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
recyclerView.removeOnScrollListener(hideExpandedViewScrollListener);
this.recyclerView = null;
}
private final RecyclerView.OnScrollListener hideExpandedViewScrollListener =
new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dx != 0 || dy != 0) {
hideExpandedStickerPreview();
}
}
};
private void positionExpandedStickerPreview(int selectedPosition) {
if (expandedStickerPreview != null) {
// Calculate the view's center (x, y), then use expandedStickerPreview's height and
// width to
// figure out what where to position it.
final ViewGroup.MarginLayoutParams recyclerViewLayoutParams =
((ViewGroup.MarginLayoutParams) recyclerView.getLayoutParams());
final int recyclerViewLeftMargin = recyclerViewLayoutParams.leftMargin;
final int recyclerViewRightMargin = recyclerViewLayoutParams.rightMargin;
final int recyclerViewWidth = recyclerView.getWidth();
final int recyclerViewHeight = recyclerView.getHeight();
final StickerPreviewViewHolder clickedViewHolder =
(StickerPreviewViewHolder)
recyclerView.findViewHolderForAdapterPosition(selectedPosition);
if (clickedViewHolder == null) {
hideExpandedStickerPreview();
return;
}
clickedStickerPreview = clickedViewHolder.itemView;
final float clickedViewCenterX =
clickedStickerPreview.getX()
+ recyclerViewLeftMargin
+ clickedStickerPreview.getWidth() / 2f;
final float clickedViewCenterY =
clickedStickerPreview.getY() + clickedStickerPreview.getHeight() / 2f;
expandedViewLeftX = clickedViewCenterX - expandedStickerPreview.getWidth() / 2f;
expandedViewTopY = clickedViewCenterY - expandedStickerPreview.getHeight() / 2f;
// If the new x or y positions are negative, anchor them to 0 to avoid clipping
// the left side of the device and the top of the recycler view.
expandedViewLeftX = Math.max(expandedViewLeftX, 0);
expandedViewTopY = Math.max(expandedViewTopY, 0);
// If the bottom or right sides are clipped, we need to move the top left positions
// so that those sides are no longer clipped.
final float adjustmentX =
Math.max(
expandedViewLeftX
+ expandedStickerPreview.getWidth()
- recyclerViewWidth
- recyclerViewRightMargin,
0);
final float adjustmentY =
Math.max(expandedViewTopY + expandedStickerPreview.getHeight() - recyclerViewHeight, 0);
expandedViewLeftX -= adjustmentX;
expandedViewTopY -= adjustmentY;
expandedStickerPreview.setX(expandedViewLeftX);
expandedStickerPreview.setY(expandedViewTopY);
}
}
private void expandPreview(int position, View clickedStickerPreview) {
if (isStickerPreviewExpanded()) {
hideExpandedStickerPreview();
return;
}
this.clickedStickerPreview = clickedStickerPreview;
if (expandedStickerPreview != null) {
positionExpandedStickerPreview(position);
final Uri stickerAssetUri = StickerPackLoader.getStickerAssetUri(stickerPack.identifier, stickerPack.getStickers().get(position).imageFileName);
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setUri(stickerAssetUri)
.setAutoPlayAnimations(true)
.build();
expandedStickerPreview.setImageResource(errorResource);
expandedStickerPreview.setController(controller);
expandedStickerPreview.setVisibility(View.VISIBLE);
recyclerView.setAlpha(EXPANDED_STICKER_PREVIEW_BACKGROUND_ALPHA);
expandedStickerPreview.setOnClickListener(v -> hideExpandedStickerPreview());
}
}
public void hideExpandedStickerPreview() {
if (isStickerPreviewExpanded() && expandedStickerPreview != null) {
clickedStickerPreview.setVisibility(View.VISIBLE);
expandedStickerPreview.setVisibility(View.INVISIBLE);
recyclerView.setAlpha(COLLAPSED_STICKER_PREVIEW_BACKGROUND_ALPHA);
}
}
private boolean isStickerPreviewExpanded() {
return expandedStickerPreview != null && expandedStickerPreview.getVisibility() == View.VISIBLE;
}
@Override
public int getItemCount() {
int numberOfPreviewImagesInPack;
numberOfPreviewImagesInPack = stickerPack.getStickers().size();
if (cellLimit > 0) {
return Math.min(numberOfPreviewImagesInPack, cellLimit);
}
return numberOfPreviewImagesInPack;
}
}
thanks in advance
ANSWER
Answered 2022-Feb-08 at 19:13It seems like every item has right padding.
You should use addItemDecoration
on your RecyclerView instead.
Or use this: https://github.com/grzegorzojdana/SpacingItemDecoration
QUESTION
I have a react-native app that runs perfectly well in debug, but fails on a release build. Running node 16.3.2 inside Windows 11 with react-native 0.63.4
Any thoughts on what to try would be greatly appreciated.
The build error from gradlew assembleRelease
is:
> Task :app:compileReleaseJavaWithJavac FAILED
C:\Projects\right-on-course-expo - ejectRelease-20220207\android\app\src\main\java\com\hordernit\rightoncourseapp\MainApplication.java:3: error: class, interface, or enum expected
package com.hordernit.rightoncourseapp;
^
1 error
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:compileReleaseJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
The MainApplication.java referred to in the error is as follows:
import expo.modules.updates.UpdatesDevLauncherController;
import expo.modules.devlauncher.DevLauncherController;
package com.hordernit.rightoncourseapp;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.hordernit.rightoncourseapp.generated.BasePackageList;
import org.unimodules.adapters.react.ReactAdapterPackage;
import org.unimodules.adapters.react.ModuleRegistryAdapter;
import org.unimodules.adapters.react.ReactModuleRegistryProvider;
import org.unimodules.core.interfaces.Package;
import org.unimodules.core.interfaces.SingletonModule;
import expo.modules.updates.UpdatesController;
import com.facebook.react.bridge.JSIModulePackage;
import com.swmansion.reanimated.ReanimatedJSIModulePackage;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
public class MainApplication extends Application implements ReactApplication {
private final ReactModuleRegistryProvider mModuleRegistryProvider = new ReactModuleRegistryProvider(
new BasePackageList().getPackageList()
);
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return DevLauncherController.getInstance().getUseDeveloperSupport();
}
@Override
protected List getPackages() {
List packages = new PackageList(this).getPackages();
packages.add(new ModuleRegistryAdapter(mModuleRegistryProvider));
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
@Override
protected JSIModulePackage getJSIModulePackage() {
return new ReanimatedJSIModulePackage();
}
@Override
protected @Nullable String getJSBundleFile() {
if (BuildConfig.DEBUG) {
return super.getJSBundleFile();
} else {
return UpdatesController.getInstance().getLaunchAssetFile();
}
}
@Override
protected @Nullable String getBundleAssetName() {
if (BuildConfig.DEBUG) {
return super.getBundleAssetName();
} else {
return UpdatesController.getInstance().getBundleAssetName();
}
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
if (!BuildConfig.DEBUG) {
UpdatesController.initialize(this);
}
DevLauncherController.initialize(this, getReactNativeHost());
if (BuildConfig.DEBUG) {
DevLauncherController.getInstance().setUpdatesInterface(UpdatesDevLauncherController.initialize(this));
}
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* @param context
* @param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class aClass = Class.forName("com.hordernit.rightoncourseapp.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
My /android/build.gradle file is as follows:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "29.0.3"
minSdkVersion = 21
compileSdkVersion = 30
targetSdkVersion = 30
}
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:4.1.0")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
maven { url 'https://www.jitpack.io' }
}
}
and the android/app/build.gradle looks like:
apply plugin: "com.android.application"
import com.android.build.OutputFile
project.ext.react = [
enableHermes: (findProperty('expo.jsEngine') ?: "jsc") == "hermes",
]
apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/expo-constants/scripts/get-app-config-android.gradle"
apply from: "../../node_modules/expo-updates/scripts/create-manifest-android.gradle"
/**
* Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices
* - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore.
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and mirrored here. If it is not set
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes", false);
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId 'com.hordernit.rightoncourseapp'
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0.0"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
release {
storeFile file('roc-app.jks')
storePassword 'snip'
keyAlias 'snip'
keyPassword 'snip'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.release
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
addUnimodulesDependencies()
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply from: "./eas-build.gradle"
ANSWER
Answered 2022-Feb-07 at 03:56Try declaring the package separately above the imports like this:
package com.hordernit.rightoncourseapp;
import expo.modules.updates.UpdatesDevLauncherController;
import expo.modules.devlauncher.DevLauncherController;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
//....
QUESTION
Before you link me to another question similar to this one, such as this or that. I will say that I have done exactly what the answers said, but my gif won't animate as it should (It is displayed though).
Here is what I've done in a function, which is displayed through the main App function Stack.Screen within a NavigationContainer and Stack.Navigator. (I'm using React Navigation to move across screens, the context here is that a button is pressed and it displays the contents of the DetailsScreen function)
function DetailsScreen({ navigation }) {
return (
Here is a gif
);
}
This displays the first still image of my gif, but doesn't animate it.
I also already went ahead and placed the implementations in the build.gradle dependencies, but it didn't do anything for me. I have a feeling the problem lies there.
implementation 'com.facebook.fresco:fresco:1.+'
// For animated GIF support
implementation 'com.facebook.fresco:animated-gif:1.+'
// For WebP support, including animated WebP
implementation 'com.facebook.fresco:animated-webp:1.+'
implementation 'com.facebook.fresco:webpsupport:1.+'
(I already checked fresco's new implementation version 2, but it still didn't help. I also tried changing from a specific version, still doesn't work)
I am using React Native version 0.67. (I tried starting it again while downgrading react-native to 0.66 and it still doesn't work.)
Also, not sure if this has to do with anything in this screenshot here, this is what I had by default and gave me this error message as soon as I opened the file, but the program launches just fine even with that on
Doing it normally in the main App() function starting first displays the gif, but still remains as a still image.
What should I do? I mean... what else can I do?
Edit:
I found the solution to the problem... it was a simple case of just cold booting the emulator I was using from android studio.
However, Tadej's answer is valid, as the view style aligning messes up the gif a bit. If you are having a similar problem and the answer doesn't help, try cold booting your emulator, or even reinstall a newer one... or alternatively, use a real android phone to test these sorts of things.
Anyway, thanks a lot for the help Tadej ! I hope this question has helped others in my situation.
Tadej Slemenšek
ANSWER
Answered 2022-Jan-20 at 17:54This worked for me. Setting height and width on Image prop did not show the gif. So I flexed it and added maxWidth and maxHeight.
const imageUrl = 'https://media.giphy.com/media/xT0xeCCINrlk96yc0w/giphy.gif';
const App = () => {
const { width } = useWindowDimensions();
return (
);
};
QUESTION
stuck at an ansible hackkerrank lab(fresco play) that asks to install nginx and postgresql and ensure they are running. But after finishing the code and running the exam it is checking for redirection of nginx server after restart to google.com. Has anyone faced this issue?
Below is my code to install and ensure services are running:
name: 'To install packages'
hosts: localhost
connection: local
become: yes
become_method: sudo
tasks:
-
apt:
name: "{{item}}"
state: present
with_items:
- nginx
- postgresql
apt: name=nginx state=latest
- name: start nginx
service:
name: nginx
state: started
apt: name=postgresql state=latest
- name: start postgresql
service:
name: postgresql
state: started
Wrote these in two separate playbooks as of now and need help in redirection of nginx to google.com
ANSWER
Answered 2021-Oct-16 at 19:22You need to write your nginx configuration file (in this case specifying to redirect traffic to google) and copy to the /etc/nginx/nginx.conf
file.
- name: write nginx.conf
template:
src:
dest: /etc/nginx/nginx.conf
After this you should restart the nginx service.
QUESTION
I have generated a .apk
file out of React Native 0.66.3
app (RN app) for test distribution by 3rd party distribution channel which only accept .apk
format. After downloading to an android phone (API 30), the app is stuck with the registration page after entering user info and didn't go any further (after user enters reg info, the RN app shall route to verification page and send the user info to backend Nodejs server). The RN app is working fine on both emulator (API 27) and running on the same Android phone (API 30, connected with USB cable). The Android Studio
used is 2021.3.1. The develop platform is macOS Big Sur.
I have no clue what is the problem. Here is the steps generating app
distributed:
Generate
app-release.aab
file. Under/android
do:
$./gradlew bundleRelease
Out of app-release.aab
file, generate a xyz_app51.apks
file with bundleTool
, with --mode=universal at the end of command:
npx bundletool build-apks --bundle=/path-to-app/android/app/build/outputs/bundle/release/app-release.aab --output=/path-to-subdir/apks/xyz_app51.apks --ks=/path-to-key/keys/key0 --ks-key-alias=androidkey0 --mode=universal
Unzip xyz_app51.apks
to xyz_app51.apk
for test distribution:
$unzip -p ./xyz_app51.apks universal.apk > xyz_app51.apk
UPDATE: android/build.gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "30.0.3"
minSdkVersion = 23
compileSdkVersion = 30
targetSdkVersion = 30
ndkVersion = "21.4.7075529"
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle:4.2.2")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenCentral()
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
maven { url 'https://maven.google.com' } //for rn image-crop-picker
maven { url 'https://www.jitpack.io' }
}
}
android/app/build.gradle:
apply plugin: "com.android.application"
import com.android.build.OutputFile
/**
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
* and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line.
*
* project.ext.react = [
* // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.android.bundle",
*
* // the entry file for bundle generation. If none specified and
* // "index.android.js" exists, it will be used. Otherwise "index.js" is
* // default. Can be overridden with ENTRY_FILE environment variable.
* entryFile: "index.android.js",
*
* // https://reactnative.dev/docs/performance#enable-the-ram-format
* bundleCommand: "ram-bundle",
*
* // whether to bundle JS and assets in debug mode
* bundleInDebug: false,
*
* // whether to bundle JS and assets in release mode
* bundleInRelease: true,
*
* // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}'
* // bundleInFreeDebug: true,
* // bundleInPaidRelease: true,
* // bundleInBeta: true,
*
* // whether to disable dev mode in custom build variants (by default only disabled in release)
* // for example: to disable dev mode in the staging build type (if configured)
* devDisabledInStaging: true,
* // The configuration property can be in the following formats
* // 'devDisabledIn${productFlavor}${buildType}'
* // 'devDisabledIn${buildType}'
*
* // the root of your project, i.e. where "package.json" lives
* root: "../../",
*
* // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
*
* // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
*
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"],
*
* // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"],
*
* // supply additional arguments to the packager
* extraPackagerArgs: []
* ]
*/
project.ext.react = [
//enableHermes: false, // clean and rebuild if changing
enableHermes: true, // for RN reanimated
]
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle" // RN vector icons
/**
* Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices
* - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore.
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and mirrored here. If it is not set
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes", true); //mirrored from project.ext.react
/**
* Architectures to build native code for in debug.
*/
def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures")
android {
ndkVersion rootProject.ext.ndkVersion
compileSdkVersion rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "com.xyz_app5"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
vectorDrawables.useSupportLibrary = true //RN image crop picker
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
if (nativeArchitectures) {
ndk {
abiFilters nativeArchitectures.split(',')
}
}
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
// Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
defaultConfig.versionCode * 1000 + versionCodes.get(abi)
}
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.implementation
into 'libs'
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
Here is the AndroidManifest.xml:
ANSWER
Answered 2021-Dec-17 at 10:56This issue occur because you API not working. Solution: First: Check your API Links It must be start with https not with http. Second: Go to the Android Manifest file and add android:usesCleartextTraffic="true" inside the application starting tag. then sync your gradle and check it.
QUESTION
I am struggling to get my GIFs to animate on the Android version of my RN application. The iOS version is animating the looping GIFs as expected but I only see a stuck "single frame" image from the GIF on the Android device.
According to the debugging and RN-documentation it's required to add a few lines of implementation
to the dependencies
within the /android/app/build.gradle, but even after cleaning the gradle (running ./gradlew clean
in the /android folder) and deleting the cache of the RN app (running react-native start --reset-cache
in the project root folder), I do not see any difference in my application.
I have googled and tried a lot. Based on my debugging adventure, I have tried and double-checked these suggestions, that seems to work for others but it doesn't seem to work for me...
- I have tried several versions of the fresco-libraries that seems to be required and I have also tried placing the lines in both the bottom as well as the top of the
dependencies
. - Some answers also suggest to add one or more lines of code to the android/app/proguard-rules.pro but this doesn't change anything either.
- I use GIFs in different ways of my application but it always has
width
andheight
included to thestyle
property on the.
- I have tried with GIF-uris from different CDNs and domains.
- Reinstalled the app on my test devices.
- Closed and reopened my code editors.
I'm using the following versions:
- Java: 11.0.12
- React Native: 0.65
- Android SDK: 30.0.2
- npm: 6.14.4
This is my full /android/app/build.gradle:
apply plugin: "com.android.application"
import com.android.build.OutputFile
project.ext.react = [
enableHermes: false, // clean and rebuild if changing
]
apply from: "../../node_modules/react-native/react.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false
def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false);
android {
ndkVersion rootProject.ext.ndkVersion
compileSdkVersion rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "com.example.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
// Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
defaultConfig.versionCode * 1000 + versionCodes.get(abi)
}
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
implementation project(':react-native-notifications')
implementation 'com.google.firebase:firebase-core:16.0.0'
implementation 'com.google.android.gms:play-services-ads:19.8.0'
implementation "androidx.appcompat:appcompat:1.0.0"
implementation 'com.facebook.fresco:fresco:2.4.0'
implementation 'com.facebook.fresco:animated-gif:2.4.0'
implementation 'com.facebook.fresco:webpsupport:2.4.0'
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply plugin: 'com.google.gms.google-services'
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
Let me know if I've missed something obvious. I am definitely more experienced in iOS-development, so it is very possible that I missed something :-)
ANSWER
Answered 2021-Aug-24 at 17:29How do I display an animated gif in React Native?
add android/app/build.gradle
// For animated GIF support
compile 'com.facebook.fresco:animated-gif:1.+'
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install fresco
You can use fresco like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the fresco component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page