I have a class named MapViewManager, in it I have a method called navigate like below:
public class MapViewManager{
...
public void navigate(double startX, double startY, double toX, double toY, long floorId, boolean flag) {
final FeatureLayer featureLayer = new FeatureLayer("navigate");
mapView.setLayerOffset(featureLayer);
mapView.addLayer(featureLayer);
final NavigateManager navigateManager = new NavigateManager();
if (flag) {
navigateManager.navigation(startX, startY, floorId, toX, toY, floorId);
}else{
navigateManager.clear();
}
navigateManager.setOnNavigateComplete(new NavigateManager.OnNavigateComplete() {
#Override
public void onNavigateComplete(NavigateManager.NavigateState navigateState,
FeatureCollection featureCollection) {
featureLayer.clearFeatures();
featureLayer.addFeatures(featureCollection);
for (int i=0;i<featureCollection.getSize();i++){
Feature feature = featureCollection.getFeature(i);
Coordinate coordinate = feature.getCentroid();
double x = coordinate.getX();
double y = coordinate.getY();
}
}
});
}
}
I want to access the variable named coordinate in onNavigateComplete callback method from outside so that other classes can use the coordinate variable to do something. How can I make it?
Add one more parameter to navigate method.
public class MapViewManager{
...
public void navigate(double startX, double startY, double toX, double toY, long floorId, boolean flag, NavigateManager.OnNavigateComplete navigation) {
final FeatureLayer featureLayer = new FeatureLayer("navigate");
mapView.setLayerOffset(featureLayer);
mapView.addLayer(featureLayer);
final NavigateManager navigateManager = new NavigateManager();
if (flag) {
navigateManager.navigation(startX, startY, floorId, toX, toY, floorId);
}else{
navigateManager.clear();
}
navigateManager.setOnNavigateComplete(navigation);
}
}
Call method from other Class :
new MapViewManager().navigate(other paramter values, new NavigateManager.OnNavigateComplete() {
#Override
public void onNavigateComplete(NavigateManager.NavigateState navigateState,
FeatureCollection featureCollection) {
featureLayer.clearFeatures();
featureLayer.addFeatures(featureCollection);
for (int i=0;i<featureCollection.getSize();i++){
Feature feature = featureCollection.getFeature(i);
Coordinate coordinate = feature.getCentroid();
navigationPoints.add(coordinate);
double x = coordinate.getX();
double y = coordinate.getY();
}
}
});
Now you can access any object anywhere.
You have to make it public by doing this:
Say your activity name is 'Main'
....
Public class Main extends AppCompatActivity{
Coordinate coor;
//in the onNavigationComplete method do this
Coordinate coordinate = //..complete this;
coor = coordinate;
…
…}
Related
I am a newbie in Android and Robolectric.
I am trying to simulate (as the topic indicates it) a drag event on a viewpager.
I have ever implemented this code and it runs on the emulator.
The matter is mostly: how can I unit test it?
Here is the unit test:
/** imports are skipped **/
#RunWith(RobolectricTestRunner.class)
#Config(manifest = "/src/main/AndroidManifest.xml")
public class TestImages {
private ImageActivity activity;
#InjectResource(R.drawable.ic_launcher)
private static Drawable image;
#Spy
private final PicturesModel picturesModel = spy(new PicturesModelImpl());
/**
* Last touched view
*/
private View lastTouchView;
/**
* Last touched X coordinate
*/
private float lastTouchX;
/**
* Last touched Y coordinate
*/
private float lastTouchY;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
final Module roboGuiceModule = RoboGuice.newDefaultRoboModule(Robolectric.application);
final Module pictureModule = Modules.override(roboGuiceModule).with(new PictureModule());
final Module testModule = Modules.override(pictureModule).with(new TestPictureModule(picturesModel));
RoboGuice.setBaseApplicationInjector(Robolectric.application, RoboGuice.DEFAULT_STAGE, testModule);
RoboInjector injector = RoboGuice.getInjector(Robolectric.application);
injector.injectMembersWithoutViews(this);
}
#Test
public void scroll_image() {
final Intent intent = new Intent(Robolectric.getShadowApplication().getApplicationContext(), ImageActivity.class);
final Album album = new Album(1, "album_1", image);
intent.putExtra("album", album);
intent.putExtra("position", 2);
intent.putExtra("imageId", 2L);
// Get the activity
activity = Robolectric.buildActivity(ImageActivity.class).withIntent(intent).create().get();
final Point point = new Point();
activity.getWindowManager().getDefaultDisplay().getSize(point);
// Get a spy viewer otherwise viewPager's width is always 0
final ViewPager viewPager = spy((ViewPager) activity.findViewById(R.id.viewPager));
viewPager.setVisibility(View.VISIBLE);
when(viewPager.getWidth()).thenReturn(point.x - 50);
// First item sent by viewPager before swipe
final int firstItem = viewPager.getCurrentItem();
// Swipe
drag(viewPager, 10F, 10F, point.x - 60F, 10F);
// Next item after swipe
final int secondItem = viewPager.getCurrentItem();
// Comparison
assertThat(firstItem).isEqualTo(2);
assertThat(secondItem).isEqualTo(3);
}
public void touchDown(View view, float x, float y) {
lastTouchX = x;
lastTouchY = y;
lastTouchView = view;
sendMotionEvent(view, MotionEvent.ACTION_DOWN, x, y);
}
public void touchMove(float x, float y) {
lastTouchX = x;
lastTouchY = y;
sendMotionEvent(lastTouchView, MotionEvent.ACTION_MOVE, x, y);
}
public void touchUp() {
sendMotionEvent(
lastTouchView, MotionEvent.ACTION_UP, lastTouchX, lastTouchY);
lastTouchView = null;
}
public void drag(View view, float xStart, float yStart,
float xEnd, float yEnd) {
touchDown(view, xStart, yStart);
touchMove(xEnd, yEnd);
touchUp();
}
private void sendMotionEvent(View view, int action, float x, float y) {
int[] screenOffset = new int[2];
view.getLocationOnScreen(screenOffset);
MotionEvent event = MotionEvent.obtain(100, 200, action,
x + screenOffset[0], y + screenOffset[1], 0);
shadowOf(event).setPointerIds(1, 2);
shadowOf(event).setPointerIndex(1);
view.onTouchEvent(event);
view.dispatchTouchEvent(event);
}
}
and the the activity:
public class ImageActivity extends RoboActivity {
#Inject
private PicturesModel picturesModel;
#InjectView(R.id.viewPager)
private ViewPager viewPager;
private PagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
final Bundle bundle = getIntent().getExtras();
if (bundle != null && !bundle.isEmpty()) {
final long id = (long) bundle.get("imageId");
final int position = (int) bundle.get("position");
final Picture picture = picturesModel.getPicture(id);
if (picture != null) {
pagerAdapter = new ImageAdapter(this, picturesModel.getAllPictures((Album) bundle.get("album")));
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(position, true);
}
}
}
}
and this is the layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/viewPager" />
Does someone has an idea how to proceed or to tell me where is my mistake?
I think you what you are looking for is the Espresso library.
It simulates UI Events and let you check the state of the view once you threw the event and it is really easy to use. Just don't forget to switch animations off in the developers settings.
i am using andengine for implementing accelerometer sensor in android. my requirement is i have to move the ball to the center of the screen using accelerometer. I am able to achieve that when the device is in lying flat position. because it uses the X and Y acceleration values for the calculation in AndEngine library.
but the problem arise when i hold the device in straight up position. the object doesn't move to the center and it always lays down to the bottom bar of the screen. however, i tried to calculate the z value at this time and inject my logic into AccelerationData class to use z value instead of y. but no success. please go through the following code and guide me what wrong i am doing.
AccelerationData.java
public class AccelerationData extends BaseSensorData {
// ===========================================================
// Constants
// ===========================================================
private static final IAxisSwap AXISSWAPS[] = new IAxisSwap[4];
static {
AXISSWAPS[Surface.ROTATION_0] = new IAxisSwap() {
#Override
public void swapAxis(final float[] pValues) {
final float x = -pValues[SensorManager.DATA_X];
final float y;
if(SensorManager.DATA_Z > -0.50 && SensorManager.DATA_Z <0.50){
y = pValues[SensorManager.DATA_Z];
}else{
y = pValues[SensorManager.DATA_Y];
}
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
AXISSWAPS[Surface.ROTATION_90] = new IAxisSwap() {
#Override
public void swapAxis(final float[] pValues) {
final float x = pValues[SensorManager.DATA_Y];
final float y = pValues[SensorManager.DATA_X];
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
AXISSWAPS[Surface.ROTATION_180] = new IAxisSwap() {
#Override
public void swapAxis(final float[] pValues) {
final float x = pValues[SensorManager.DATA_X];
final float y = -pValues[SensorManager.DATA_Y];
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
AXISSWAPS[Surface.ROTATION_270] = new IAxisSwap() {
#Override
public void swapAxis(final float[] pValues) {
final float x = -pValues[SensorManager.DATA_Y];
final float y = -pValues[SensorManager.DATA_X];
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
}
...
...
}
here i am showing the usage of z value only when device is at 0 degree. any help would be greatly appreciated.
I've been working on the example from http://obviam.net/index.php/a-very-basic-the-game-loop-for-android/ In this I want to make few changes.
Speed.java
public class Speed {
public static final int DIRECTION_RIGHT = 1;
public static final int DIRECTION_LEFT = -1;
public static final int DIRECTION_UP = -1;
public static final int DIRECTION_DOWN = 1;
private float xv = 1; // velocity value on the X axis
private float yv = 1; // velocity value on the Y axis
private int xDirection = DIRECTION_RIGHT;
private int yDirection = DIRECTION_DOWN;
public Speed() {
this.xv = 1;
this.yv = 1;
}
public Speed(float xv, float yv) {
this.xv = xv;
this.yv = yv;
}
public float getXv() {
return xv;
}
public void setXv(float xv) {
this.xv = xv;
}
public float getYv() {
return yv;
}
public void setYv(float yv) {
this.yv = yv;
}
public int getxDirection() {
return xDirection;
}
public void setxDirection(int xDirection) {
this.xDirection = xDirection;
}
public int getyDirection() {
return yDirection;
}
public void setyDirection(int yDirection) {
this.yDirection = yDirection;
}
// changes the direction on the X axis
public void toggleXDirection() {
xDirection = xDirection * -1;
}
// changes the direction on the Y axis
public void toggleYDirection() {
yDirection = yDirection * -1;
}
}
Using this, the image moves in all directions. Now I just want to limit this movement from bottom to top. And the functionality for onclick is that, we can click and drag the image to required position. I want to replace that with just make the image to disappear or go to another activity. Please help me in making changes to this code. Thanks in advance.
if you have used SurfaceView then in onDraw(Canvas canvas) method the code is for moving image from bottom to top is something like this.
canvas.drawBitmap(bitmap,xPoint,yPoint,paint);
where bitmap is an image(Bitmap which you want to move),xPoint is the x coordinate,yPoint is the y coordinate and paint is a Paint which is also can be null.
and for bottom to top movement just update
yPoint = yPoint - 1;
in any thread before onDraw() call.
May this help you.
I have 10 picture on scene as sprites.And they are in an array.The pictures(sprites) are moving on scene by MoveModifier.
I want this: When I touch any picture,the picture which is I touched should be invisible.
my codes doesn't work because of 19. line(circles[i].setVisible(false);)
eclipse says me do i(variable) as final.I can't do that because i should change it's index of array.What can I do?
final int totalCircleNumber=10;
int circleNumber=0;
private Sprite[] circles = new Sprite[totalCircleNumber];
private Runnable mStartCircle = new Runnable() {
public void run() {
int i=circleNumber++;
Scene scene = Level1Activity.this.mEngine.getScene();
float startX = randomNumber.nextFloat()*(CAMERA_WIDTH);
float startY = -64.0f;
float finishX= randomNumber.nextFloat()*(CAMERA_WIDTH);
float finishY= CAMERA_HEIGHT+64.0f;
int j= randomNumber.nextInt(50);
circles[i] = new Sprite(startX, startY, textRegCircle[j]){
#Override
public boolean onAreaTouched(final TouchEvent pAreaTouchEvent,final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
if(pAreaTouchEvent.isActionDown())
{
circles[i].setVisible(false);
}
return true;
}
};
scene.registerTouchArea(circles[i]);
circles[i].registerEntityModifier(
(IEntityModifier) new SequenceEntityModifier (
new MoveModifier(velocityOfCircle, circles[i].getX(), finishX,
circles[i].getY(), finishY)));
scene.getLastChild().attachChild(circles[i]);
if (circleNumber < totalCircleNumber){
mHandler.postDelayed(mStartCircle,second);
}
}
};
replace:
circles[i].setVisible(false);
with
this.setVisible(false);
When I use MapController.setZoom(x) and, for instance, zoom from level 5 to 15 the zoom is perform very fast and often the map tiles of the new level are not loaded.
This does not look so good to the user. Any Maps build in function to change this to a more slow zoom so tiles can be loaded, or at least almost loaded, before level 15 is reached?
Best regards
P
A simpler way is to take advantage of the MapController.zoomIn() method that provides some simple animation for zooming a step level.
Here's some code:
// a Quick runnable to zoom in
int zoomLevel = mapView.getZoomLevel();
int targetZoomLevel = 18;
long delay = 0;
while (zoomLevel++ < targetZoomLevel) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
mapController.zoomIn();
}
}, delay);
delay += 350; // Change this to whatever is good on the device
}
What it does is create a sequence of delayed runnables each one of which will call zoomIn() 350ms after the previous one.
This assumes that you have a Handler attached to your main UI thread called 'handler'
:-)
There's no simple way to do this. However, I can help you out.
Firstly, here's a free gift of one of my personal utility classes, Tween.java:
import android.os.Handler;
public class Tween {
public static interface TweenCallback {
public void onTick(float time, long duration);
public void onFinished();
}
long start;
long duration;
Handler handler;
TweenCallback callback;
public Tween(TweenCallback callback) {
handler = new Handler();
this.callback = callback;
}
public void start(final int duration) {
start = android.os.SystemClock.uptimeMillis();
this.duration = duration;
tickRunnable.run();
}
public void stop() {
handler.removeCallbacks(tickRunnable);
}
Runnable tickRunnable= new Runnable() {
public void run() {
long now = android.os.SystemClock.uptimeMillis();
float time = now - start;
boolean finished = (time >= duration);
if (finished) {
time = duration;
}
callback.onTick(time, duration);
if (!finished) {
handler.post(tickRunnable);
}
else {
callback.onFinished();
}
}
};
//
// Tweening functions. The 4 parameters are :
//
// t - time, ranges from 0 to d
// b - begin, i.e. the initial value for the quantity being changed over time
// c - change, the amount b will be changed by at the end
// d - duration, of the transition, normally in milliseconds.
//
// All were adapted from http://jstween.sourceforge.net/Tween.js
//
public static float strongEaseInOut(float t, float b, float c, float d) {
t/=d/2;
if (t < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
}
public static float regularEaseIn(float t, float b, float c, float d) {
return c*(t/=d)*t + b;
}
public static float strongEaseIn(float t, float b, float c, float d) {
return c*(t/=d)*t*t*t*t + b;
}
}
What I recommend you do is use MapController.zoomToSpan() in conjunction with a Tween... here's some completely untested code that should work, maybe with a tweak or two, you just pass it the target lat & lon spans. :
public void slowZoom(int latE6spanTarget, int lonE6spanTarget) {
final float initialLatE6span = mapView.getLatitudeSpan();
final float initialLonE6span = mapView.getLongitudeSpan();
final float latSpanChange = (float)(latE6spanTarget - initialLatE6span);
final float lonSpanChange = (float)(lonE6spanTarget - initialLonE6span);
Tween tween = new Tween(new Tween.TweenCallback() {
public void onTick(float time, long duration) {
float latSpan = Tween.strongEaseIn(time, initialLatE6span, latSpanChange, duration);
float lonSpan = Tween.strongEaseIn(time, initialLonE6span, lonSpanChange, duration);
mapView.getController().zoomToSpan((int)latSpan, (int)lonSpan);
}
public void onFinished() {
}
});
tween.start(5000);
}