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);
Related
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;
…
…}
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'm trying to fix this problem for more than 2 days now and have become quite desperate.
I want to write a 'Checkers-like' board game for android. The game engine itself is kinda complete but i have problems with updating the views.
I wrote a little example class to demonstrate my problem:
public class GameEngineView extends View {
private static final String TAG = GameEngineView.class.getSimpleName();
private int px;
private int py;
private int cx;
private int cy;
private boolean players_move;
private int clickx;
private int clicky;
Random rgen;
private RefreshHandler mRedrawHandler = new RefreshHandler();
class RefreshHandler extends Handler {
#Override
public void handleMessage(Message msg) {
GameEngineView.this.update();
GameEngineView.this.invalidate();
Log.d(TAG, "invalidate()");
}
public void sleep(long delayMillis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
};
public GameEngineView(Context context) {
super(context);
setFocusable(true);
players_move = true;
rgen = new Random();
}
public void update() {
updateGame();
Log.d(TAG, "update -> sleep handler");
mRedrawHandler.sleep(100);
}
public void updateGame() {
if(players_move) {
px = clickx;
py = clicky;
} else {
calcAIMove();
switchMove();
}
}
public void switchMove() {
players_move = !players_move;
}
public void calcAIMove() {
for(int i = 0; i < 20000; i++) {
cx = rgen.nextInt(getWidth());
cy = rgen.nextInt(getHeight());
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG, "event");
int eventaction = event.getAction();
if(eventaction == MotionEvent.ACTION_DOWN) {
Log.d(TAG, "action_down");
clickx = (int) event.getX();
clicky = (int) event.getY();
switchMove();
update();
}
return super.onTouchEvent(event);
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint green = new Paint();
green.setColor(Color.GREEN);
Paint red = new Paint();
red.setColor(Color.RED);
canvas.drawColor(Color.BLACK);
canvas.drawCircle(px, py, 25, green);
canvas.drawCircle(cx, cy, 25, red);
}
}
The function calcAIMove() just burns time to simulate a real evaluation of the position in a board game.
Now my Problem is: If the player clicks(makes a move) the green ball is first drawn when the ai move calculation has been complete. So both moves are drawn at the same time.
I wonder HOW to accomplish this:
-Player clicks
-green Ball is drawn
-AI calculates
-red ball is drawn
-and so on..
When searching the web i found a lot of game loop examples but they all need a Thread with constant polling.. it should be possible without this since the whole program runs sequentially .. right?
Hoping for advice.
thanks,
Dave
Here is how your game could work:
user makes a move
game view is updated
game switches to CPU's turn
sleep to simulate CPU player thinking (if move computation is trivial)
compute CPU's move
game view is updated
game switches to player's turn
There is no need for constant polling in a turn-based game like this. The only place you should have sleep is in step 4, so you can remove it from the other areas (no need for the old update() method which is just a delayed call to updateGame()).
One way to implement this is to simply delay the call to calcAIMove() and switchMove() by putting it into a Runnable and using Handler.postDelayed() or similar.
I don't see how you are disabling touch events when it is the CPU's turn, which can lead to a host of other problems if switchMove() and update() are still being called...
In your game loop you can use a instance of TimerTask to ensure certain delay between greenBall and some other drawing task. Game tutorials like Snake and LunarLander are great references on when and if you need to invalidate your View. Hope this helps a little!
ok so the answer provided by antonyt helped me solve this.. I provide the corrected code for other interested ones.
public class GameEngineView extends View {
private static final String TAG = GameEngineView.class.getSimpleName();
private int px;
private int py;
private int cx;
private int cy;
private boolean players_move;
private int clickx;
private int clicky;
Random rgen;
/**
* Create a simple handler that we can use to cause animation to happen. We
* set ourselves as a target and we can use the sleep()
* function to cause an update/invalidate to occur at a later date.
*/
private RefreshHandler mRedrawHandler = new RefreshHandler();
class RefreshHandler extends Handler {
#Override
public void handleMessage(Message msg) {
GameEngineView.this.update();
}
public void sleep(long delayMillis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
};
public GameEngineView(Context context) {
super(context);
setFocusable(true);
players_move = true;
rgen = new Random();
}
public void update() {
if(players_move) {
Log.d(TAG, "new player x");
px = clickx;
py = clicky;
GameEngineView.this.invalidate();
switchMove();
mRedrawHandler.sleep(100);
} else {
Log.d(TAG, "new ai x");
calcAIMove();
GameEngineView.this.invalidate();
switchMove();
}
Log.d(TAG, "update -> sleep handler");
}
public void switchMove() {
players_move = !players_move;
}
public void calcAIMove() {
for(int i = 0; i < 100000; i++) {
cx = rgen.nextInt(getWidth());
cy = rgen.nextInt(getHeight());
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG, "event");
int eventaction = event.getAction();
if(players_move && eventaction == MotionEvent.ACTION_DOWN) {
Log.d(TAG, "action_down");
clickx = (int) event.getX();
clicky = (int) event.getY();
update();
}
return super.onTouchEvent(event);
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.BLACK);
Paint green = new Paint();
green.setColor(Color.GREEN);
Paint red = new Paint();
red.setColor(Color.RED);
canvas.drawCircle(px, py, 25, green);
canvas.drawCircle(cx, cy, 25, red);
}
}