LibGDX: How to keep displaying actor after drag (drag off) - drag-and-drop

I have implemented drag and drop, but the problem is after user releases the drag. The dragged actor is dissapear from the screen. How to move actor to its new location or return to its location if it is dropped not in its proper locations?
Thanks for your answers.
Regards,
Alfa
'
final DragAndDrop dragAndDrop = new DragAndDrop();
final Box sourceBox = boxList.get(0);
final Box targetBox = boxHolderList.get(0);
Source source = new Source(sourceBox) {
#Override
public void dragStop(InputEvent event, float x, float y,
int pointer, Payload payload, Target target) {
Box sourceBox = (Box) payload.getDragActor();
if (target == null){
sourceBox.setPosition(sourceBox.getX(), sourceBox.getY());
}
else{
Box targetBox = (Box) target.getActor();
sourceBox.setPosition(targetBox.getX(), targetBox.getY());
}
}
#Override
public Payload dragStart(InputEvent event, float x, float y, int pointer) {
dragAndDrop.setDragActorPosition(-1*sourceBox.getWidth()/2, 1*sourceBox.getHeight()/2);
Payload payload = new Payload();
payload.setDragActor(sourceBox);
Label validLabel = new Label("Valid!", skin);
validLabel.setColor(0, 1, 0, 1);
payload.setValidDragActor(validLabel);
Label invalidLabel = new Label("Invalid!", skin);
invalidLabel.setColor(1, 0, 0, 1);
payload.setInvalidDragActor(invalidLabel);
return payload;
}
};

this drag and drop method is quite mesh, you may try this
yourActor.addListener(new DragListener(){
public void touchDragged(InputEvent event, float x, float y, int pointer) {
yourActor.moveBy(x-yourActor.getWidth()/2,y-yourActor.getHeight()/2);
}});

Related

JavaFX bind PathTransition's element coordinates

I'd like to have a path transition in such a way, that the path behaves relative to the window size, even when the size is changed during the animation. Furthermore, when the animation is completed, the animated element should use the stay at the relative destination location.
tileWidthProperty and tileHeightProperty are class members that I added for convinience and they simply divide the main pane's size in eights.
This is the code I have:
public void applyMove(final Ellipse toBeMoved, final int startCol, final int startRow, final int endCol, final int endRow)
{
Platform.runLater(() ->
{
final Path path = new Path();
final MoveTo startingPoint = new MoveTo();
final LineTo endPoint = new LineTo();
startingPoint.xProperty().bind(tileWidthProperty.multiply(startCol).add(tileWidthProperty.divide(2)));
startingPoint.yProperty().bind(tileHeightProperty.multiply(startRow).add(tileHeightProperty.divide(2)));
endPoint.xProperty().bind(tileWidthProperty.multiply(endCol).add(tileWidthProperty.divide(2)));
endPoint.yProperty().bind(tileHeightProperty.multiply(endRow).add(tileHeightProperty.divide(2)));
path.getElements().add(startingPoint);
path.getElements().add(endPoint);
toBeMoved.centerXProperty().unbind();
toBeMoved.centerYProperty().unbind();
PathTransition transition = new PathTransition(Duration.millis(10000), path, toBeMoved);
transition.setOrientation(PathTransition.OrientationType.NONE);
transition.setCycleCount(1);
transition.setAutoReverse(false);
//bind the node at the destination.
transition.setOnFinished(event ->
{
toBeMoved.centerXProperty().bind(tileWidthProperty.multiply(endCol).add(tileWidthProperty.divide(2)));
toBeMoved.centerYProperty().bind(tileHeightProperty.multiply(endRow).add(tileHeightProperty.divide(2)));
toBeMoved.setTranslateX(0.0);
toBeMoved.setTranslateY(0.0);
});
transition.play();
});
}
The col and row parameters are integers that are known to be 0 <= x < 8. They are the column and row of the tile position in the 8*8 grid.
The binding of the MoveTo and LineTo elements, however does not seem to have any effect.
First of all, once any standard Animation is started it does not change parameters.
So if anything changes, you have to stop the animation and start it again with new parameters.
I noticed you're trying to bind centerX and centerY after the transition is complete, which is wrong: PathTransition moves elements using translateX and translateY.
And for better debug you can actually add Path to the scene graph to see where your element will go.
Path path = new Path();
parent.getChildren().add(path);
I assume that tileWidthProperty and tileHeightProperty are bound to the actual parent size using something like this:
tileWidthProperty.bind(parent.widthProperty().divide(8));
tileHeightProperty.bind(parent.heightProperty().divide(8));
So I created example just to show how it might look like.
import javafx.animation.PathTransition;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Main extends Application {
private Pane parent;
private final DoubleProperty
tileWidthProperty = new SimpleDoubleProperty(),
tileHeightProperty = new SimpleDoubleProperty();
private EllipseTransition ellipseTransition;
#Override
public void start(Stage primaryStage) {
this.parent = new Pane();
tileWidthProperty.bind(parent.widthProperty().divide(8));
tileHeightProperty.bind(parent.heightProperty().divide(8));
// create ellipse
final Ellipse ellipse = new Ellipse(25., 25.);
parent.getChildren().add(ellipse);
// show the stage
primaryStage.setScene(new Scene(parent, 800, 800));
primaryStage.show();
// create listeners that listen to size changes
InvalidationListener sizeChangeListener = l -> {
if(ellipseTransition != null) {
// refreshAndStart returns null if transition is completed
// let's call it delayed cleanup :)
ellipseTransition = ellipseTransition.refreshAndStart();
} else {
System.out.println("ellipseTransition cleaned up!");
}
};
// add listeners to the corresponding properties
tileWidthProperty.addListener(sizeChangeListener);
tileHeightProperty.addListener(sizeChangeListener);
// move ellipse 0,0 -> 7,7
applyMove(ellipse, 0, 0, 7, 7, Duration.millis(5000));
// interrupt transition at the middle, just for fun
/*new Thread(() -> {
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
return;
}
applyMove(ellipse, 2, 3, 4, 5, Duration.millis(1000));
}).start();*/
}
public void applyMove(final Ellipse toBeMoved, final int startCol, final int startRow, final int endCol, final int endRow, final Duration duration) {
Platform.runLater(() -> {
// if transition is still up, then stop it
if(ellipseTransition != null) {
ellipseTransition.finish();
}
// and create a new one
ellipseTransition = new EllipseTransition(toBeMoved, startCol, startRow, endCol, endRow, Duration.ZERO, duration, 0);
// then start it
ellipseTransition.start();
});
}
// I decided to write separate class for the transition to make it more convenient
private class EllipseTransition {
// these variables are the same you used in your code
private final Path path;
private final Ellipse ellipse; // this one was "toBeMoved"
private final int startCol, startRow, endCol, endRow;
private final Duration duration;
private final PathTransition transition;
// if we change parent size in the middle of the transition, this will give the new transition information about where we were.
private Duration startTime;
// we call System.currentTimeMillis() when we start
private long startTimestamp;
// if true, transition would not start again
private boolean finished;
public EllipseTransition(Ellipse ellipse, int startCol, int startRow, int endCol, int endRow, Duration startTime, Duration duration, long realStartTimestamp) {
this.path = new Path();
this.ellipse = ellipse;
this.startCol = startCol;
this.startRow = startRow;
this.endCol = endCol;
this.endRow = endRow;
this.startTime = startTime;
this.duration = duration;
this.transition = new PathTransition();
// applyMove passes 0, because we don't know our start time yet
this.startTimestamp = realStartTimestamp;
}
// this is called right before starting the transition
private void init() {
// show path for debugging
parent.getChildren().add(path);
// binding values here is useless, you can compute everything in old-fashioned way for better readability
final MoveTo startingPoint = new MoveTo();
startingPoint.setX(tileWidthProperty.get() * startCol + tileWidthProperty.get() / 2.);
startingPoint.setY(tileHeightProperty.get() * startRow + tileHeightProperty.get() / 2.);
final LineTo endPoint = new LineTo();
endPoint.setX(tileWidthProperty.get() * endCol + tileWidthProperty.get() / 2);
endPoint.setY(tileHeightProperty.get() * endRow + tileHeightProperty.get() / 2);
path.getElements().clear(); // clear paths from the last time
path.getElements().add(startingPoint);
path.getElements().add(endPoint);
ellipse.translateXProperty().unbind();
ellipse.translateYProperty().unbind();
transition.setNode(ellipse);
transition.setDuration(duration);
transition.setPath(path);
transition.setOrientation(PathTransition.OrientationType.NONE);
transition.setCycleCount(1);
transition.setAutoReverse(false);
transition.setOnFinished(event ->
{
// bind ellipse to the new location
ellipse.translateXProperty().bind(tileWidthProperty.multiply(endCol).add(tileWidthProperty.divide(2)));
ellipse.translateYProperty().bind(tileHeightProperty.multiply(endRow).add(tileHeightProperty.divide(2)));
// cleanup
stop();
// mark as finished
finished = true;
});
}
// stops the transition
private void stop() {
// remove debug path ( added it in init() )
parent.getChildren().remove(path);
transition.stop();
}
// starts the transition
public void start() {
if(finished) {
return;
}
init(); // initialize parameters
// start from the place where previous we stopped last time
// if we did not stop anywhere, then we start from beginning (applyMove passes Duration.ZERO)
this.transition.playFrom(startTime);
// applyMove passes 0, as it doesn't know when transition will start
// but now we know
if(this.startTimestamp == 0) {
this.startTimestamp = System.currentTimeMillis();
}
}
// stops the transition
public void finish() {
stop();
finished = true;
}
// stops and refreshes the transition.
// that will continue transition but for new values
private void refresh() {
// stop the transition
stop();
// determine how much time we spend after transition has started
long currentDuration = System.currentTimeMillis() - startTimestamp;
// update startTime to the current time.
// when we call start() next time, transition will continue, but with new parameters
this.startTime = Duration.millis(currentDuration);
}
// this method is called from change listener
public EllipseTransition refreshAndStart() {
if(finished) {
// return null to the listener
// we want to cleanup completely
return null;
}
// refresh new values and start
refresh(); start();
return this;
}
}
public static void main(String[] args) {
launch(args);
}
}

Need help on Android car game [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm developing a 2D car game for my University project.
I have developed it up to the point that user's car can move and traffic cars come from above. But I have no clue about how to destroy the user's car when it collied with a traffic car. Can anyone tell how to detect collision and after that how to destroy it.
public class MainActivity extends BaseGameActivity{
Scene scene; // declare a scene object
protected static final float CAMERA_WIDTH = 800; // define camera width
protected static final float CAMERA_HEIGHT = 520; //define camera height
/*----- background -----------*/
BitmapTextureAtlas backbitmapTextureAtlas; // declare a bitmap texture
ITextureRegion backiTextureRegion; // declare a i texture region to hold image
Sprite backsPlayer; // sprite to display the image
PhysicsWorld backpWorld;
SensorManager backsensor;
Vector2 backvec;
ITexture backparallax_background;
protected VertexBufferObjectManager backvbom;
org.andengine.engine.camera.Camera camera;
/*----- /background -----------*/
/*----user's car---------*/
BitmapTextureAtlas bitmapTextureAtlas;
ITextureRegion iTextureRegion;
Vector2 vec;
PhysicsWorld pWorld;
SensorManager sensor;
Sprite sPlayer;
/*----/user's car---------*/
/*------ traffic cars----------*/
BitmapTextureAtlas bitmapTextureAtlasTraffic1;
ITextureRegion iTextureRegionTraffic1;
Sprite sPlayerTraffic1;
BitmapTextureAtlas bitmapTextureAtlasTraffic2;
ITextureRegion iTextureRegionTraffic2;
Sprite sPlayerTraffic2;
BitmapTextureAtlas bitmapTextureAtlasTraffic3;
ITextureRegion iTextureRegionTraffic3;
Sprite sPlayerTraffic3;
BitmapTextureAtlas bitmapTextureAtlasTraffic4;
ITextureRegion iTextureRegionTraffic4;
Sprite sPlayerTraffic4;
MoveXModifier mod1;
MoveXModifier mod2;
MoveXModifier mod3;
MoveXModifier mod4;
/*------ /traffic cars----------*/
#Override
public EngineOptions onCreateEngineOptions() {
// TODO Auto-generated method stub
camera = new org.andengine.engine.camera.Camera(0,0,CAMERA_WIDTH,CAMERA_HEIGHT); // create camera
EngineOptions options= new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH,CAMERA_HEIGHT), camera); //create engine options
return options;
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws Exception {
// TODO Auto-generated method stub
/* ---------------parallax back code------------------*/
backparallax_background = new AssetBitmapTexture(this.getTextureManager(), this.getAssets(), "gfx/back2.png");
backiTextureRegion = TextureRegionFactory.extractFromTexture(this.backparallax_background);
this.backparallax_background.load();
/* ---------------/parallax back code------------------*/
loadGfx(); // load user's car
loadTraffic();
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
/*--------load traffic cars------------*/
private void loadTraffic() {
// TODO Auto-generated method stub
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); // give the path of image folder
bitmapTextureAtlasTraffic1 = new BitmapTextureAtlas(getTextureManager(), 256, 256);// create a bit map to hold the picture and give size according to the image
iTextureRegionTraffic1 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapTextureAtlasTraffic1, this, "traffic1.png", 0,0);
bitmapTextureAtlasTraffic1.load();
//----- traffic 2--------------
bitmapTextureAtlasTraffic2 = new BitmapTextureAtlas(getTextureManager(), 256, 256);// create a bit map to hold the picture and give size according to the image
iTextureRegionTraffic2 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapTextureAtlasTraffic2, this, "traffic2.png", 0,0);
bitmapTextureAtlasTraffic2.load();
//----- traffic 3--------------
bitmapTextureAtlasTraffic3 = new BitmapTextureAtlas(getTextureManager(), 256, 256);// create a bit map to hold the picture and give size according to the image
iTextureRegionTraffic3 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapTextureAtlasTraffic3, this, "traffic3.png", 0,0);
bitmapTextureAtlasTraffic3.load();
//----- traffic 4--------------
bitmapTextureAtlasTraffic4 = new BitmapTextureAtlas(getTextureManager(), 256, 256);// create a bit map to hold the picture and give size according to the image
iTextureRegionTraffic4 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapTextureAtlasTraffic4, this, "traffic4.png", 0,0);
bitmapTextureAtlasTraffic4.load();
}
/*--------load user's car------------*/
private void loadGfx() {
// TODO Auto-generated method stub
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); // give the path of image folder
bitmapTextureAtlas = new BitmapTextureAtlas(getTextureManager(), 256, 256);// create a bit map to hold the picture and give size according to the image
iTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapTextureAtlas, this, "usercar.png", 0,0);
bitmapTextureAtlas.load();
}
/*--------load user's car------------*/
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws Exception {
// TODO Auto-generated method stub
scene = new Scene(); // create the object of scene
/*------ parallax background---------*/
final AutoParallaxBackground auto_background = new AutoParallaxBackground(0, 0, 0, 200);
final Sprite background_sprite = new Sprite(0,0, this.backiTextureRegion,backvbom);
auto_background.attachParallaxEntity(new ParallaxEntity(1.7f,background_sprite));
scene.setBackground(auto_background);
pOnCreateSceneCallback.onCreateSceneFinished(scene);
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
// TODO Auto-generated method stub
// set traffic car1
sPlayerTraffic1 = new Sprite(10,350,iTextureRegionTraffic1,this.mEngine.getVertexBufferObjectManager());
sPlayerTraffic2 = new Sprite(300,280,iTextureRegionTraffic2,this.mEngine.getVertexBufferObjectManager());
sPlayerTraffic3 = new Sprite(400,190,iTextureRegionTraffic3,this.mEngine.getVertexBufferObjectManager());
sPlayerTraffic4 = new Sprite(50,70,iTextureRegionTraffic4,this.mEngine.getVertexBufferObjectManager());
mod1=new MoveXModifier(5,-600,800){
#Override
protected void onModifierFinished(IEntity pItem) {
// TODO Auto-generated method stub
Random r = new Random();
int y = r.nextInt(370-350)+350;// set y randomly
int speed = r.nextInt(3-2)+3; // set speed randomly
sPlayerTraffic1.setY(y); // set y
int x = r.nextInt(800-500)+200; // set x randomly
x = -x;
mod1.reset(speed, x, 800);
super.onModifierFinished(pItem);
}
};// moving down the traffic1 car
mod2=new MoveXModifier(4,200,800){
#Override
protected void onModifierFinished(IEntity pItem) {
// TODO Auto-generated method stub
Random r = new Random();
int y = r.nextInt(300-285)+285; // set y randomly
int speed = r.nextInt(5-3)+3; // set speed randomly
sPlayerTraffic2.setY(y); // set y
int x = r.nextInt(600-200)+200; // set x randomly
x = -x;
mod2.reset(speed, x, 800);
super.onModifierFinished(pItem);
}
};// moving down the traffic2 car
mod3=new MoveXModifier(3,-600,800){
#Override
protected void onModifierFinished(IEntity pItem) {
// TODO Auto-generated method stub
Random r = new Random();
int y = r.nextInt(190-150)+150;
int speed = r.nextInt(3-2)+2;
if(speed == 2){
y = 150;
}
sPlayerTraffic3.setY(y);
int x = r.nextInt(2000-800)+800;
x = -x;
mod3.reset(speed, x, 800);
super.onModifierFinished(pItem);
}
};// moving down the traffic3 car
mod4=new MoveXModifier(3,50,800){
#Override
protected void onModifierFinished(IEntity pItem) {
// TODO Auto-generated method stub
Random r = new Random();
int y = r.nextInt(100-70)+70;
int speed = r.nextInt(3-2)+2;
sPlayerTraffic4.setY(y);
int x = r.nextInt(600-200)+200;
x = -x;
mod4.reset(speed, x, 800);
super.onModifierFinished(pItem);
}
};// moving down the traffic4 car
sPlayerTraffic1.registerEntityModifier(mod1);
sPlayerTraffic2.registerEntityModifier(mod2);
sPlayerTraffic3.registerEntityModifier(mod3);
sPlayerTraffic4.registerEntityModifier(mod4);
//now set the x,y coordination of the image to display the right position we want
sPlayer = new Sprite(500,350,iTextureRegion,this.mEngine.getVertexBufferObjectManager()){ // user's car x,y
// touch event for user's car
#Override
public boolean onAreaTouched(org.andengine.input.touch.TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY)
{
this.setPosition(500 , pSceneTouchEvent.getY());
//website code
this.setPosition(pSceneTouchEvent.getX(),
this.getY());
//Detects if player is outside of bounds
final float width = this.getWidth();
final float height = this.getHeight();
float x = pSceneTouchEvent.getX() - width / 2 ;
float y = pSceneTouchEvent.getY() - height / 2;
if (x < 0)
x = 0;
if (y < 65) // right side of the road
y = 65;
if (x > (CAMERA_WIDTH - width))
x = CAMERA_WIDTH - width;
if (y > (CAMERA_HEIGHT - height-70)) // left side of the road
y = (CAMERA_HEIGHT - height-70);
this.setPosition(500, y);
return true;
}
};
//touch ----------------------------------------------------------
scene.registerTouchArea(sPlayer);
//-----------------------------------------------------------------
this.scene.attachChild(sPlayer);
this.scene.attachChild(sPlayerTraffic1);
this.scene.attachChild(sPlayerTraffic2);
this.scene.attachChild(sPlayerTraffic3);
this.scene.attachChild(sPlayerTraffic4);
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
}
private ContactListener createContactListener()
{
ContactListener contactListener = new ContactListener()
{
#Override
public void beginContact(Contact contact)
{
final Fixture x1 = contact.getFixtureA();
final Fixture x2 = contact.getFixtureB();
if(x1==PlayerBody && x2==EnemyBody){
DestroyMethod();
}
}
};
return contactListener;
}
YourPhysicsWorld.setContactListener(createContactListener());
private void DestroyMethod(){
YourPhysicsWorld.destroyBody(EnemyBody);
}

JavaFX: Make dragged node visible

I want to drag and drop nodes between flowpanes. I implemented the drag and drop in this way:
public class TouchTask extends BorderPane{
setOnDragDetected(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
Dragboard dragboard = startDragAndDrop(TransferMode.ANY);
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putString(TASK_DRAG_KEY);
dragboard.setContent(clipboardContent);
event.consume();
}
});
}
The drag and drop works fine, but the problem is, that the node is not moved during the drag and drop gesture. I wanted to implement this drag and drop so that the node has the same position as the mouse during the gesture.
I tried to implement this in the following way:
onMousePressedProperty().set(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
// record the current mouse X and Y position on Node
mousex = event.getSceneX();
mousey = event.getSceneY();
x = getLayoutX();
y = getLayoutY();
if (isMoveToFront()) {
toFront();
}
}
});
onMouseDraggedProperty().set(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
// Get the exact moved X and Y
double offsetX = event.getSceneX() - mousex;
double offsetY = event.getSceneY() - mousey;
x += offsetX;
y += offsetY;
double scaledX = x;
double scaledY = y;
setLayoutX(scaledX);
setLayoutY(scaledY);
// again set current Mouse x AND y position
mousex = event.getSceneX();
mousey = event.getSceneY();
event.consume();
}
});
But with this solution, the node is only moved for like 3 pixel and then it stops.

Is there any way to find a string's position and click on it using robotium?

I have the following list appearing on UI of an android application which tells about the date and the temperature on that date.
temp degree
11/01 --.-- c
11/02 21.7 c
11/03 22.5 c
Here I want to find the position of string "--.--" and then click on it, so that I can update the list. Is there any way to find the position of string? I know that solo.searchText() will tell whether the string is present or not, but what about the position?
// i think it will help you
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
// TODO Auto-generated method stub
if(yourliststring.trim().equals("--.--"))
{
//your condition
}
else
{
//your condition
}
}
});
I got a simple way to find and click on the string
if(solo.searchText("--.--")){
solo.clickLongOnText("--.--");
}
All I need is to click on the string "--.--".
I'm not sure what position you need, however if you need position on screen you can simple do:
TextView textView = solo.getText("--.--"); // or solo.getText(Pattern.quote("--.--")); if needed
int[] xy = new int[2];
textView.getLocationOnScreen(xy);
final int viewWidth = textView.getWidth();
final int viewHeight = textView.getHeight();
final float x = xy[0] + (viewWidth / 2.0f);
final float y = xy[1] + (viewHeight / 2.0f);
this way you have central point of view (x, y).
If you need position of text in list, you can do:
private int getPosition(ListView listView, String text) {
for (int i = 0; i < listView.getAdapter().getCount(); i++) {
Object o = listView.getAdapter.getItemAtPosition(i);
if (o instanceof TextView) {
if (((TextView)o).getText().toString().equals(text)) {
return i;
}
}
}
return -1; // not found
}
you can call it for instance this way (set proper parameters):
int position = getPosition((ListView) solo.getView(ListView.class, 0), "--.--");
Everything written without testing and even compiling, however main idea should be fine.

Moving a body from one position to another on button press

I have a problem where the player releases a power attack,this powerattack must move upto a certain position and then get detached,how can i achieve this? I tried using setvelocity but it didnt work that well...pls help!!
Ok here's my attack method which is called when the button is pressed:
public void powerattack() {
float startBulletX = player.getX() + 30; //Get X position of character body
float startBulletY = player.getY(); //Get Y position of character body
final Sprite bullet = new Sprite(startBulletX, startBulletY,
resourcesManager.special_attack, vbom); //The special attack sprite
final FixtureDef bulletFixtureDef1 = PhysicsFactory.createFixtureDef(0,
0, 0, false, CATEGORYBIT_KNIFE, MASKBIT_KNIFE, (short) 0);
this.mBulletBody = PhysicsFactory.createBoxBody(physicsWorld, bullet,
BodyType.DynamicBody, bulletFixtureDef1);
mBulletBody.setLinearVelocity(20f,0);
this.physicsWorld.registerPhysicsConnector(new PhysicsConnector(bullet,
this.mBulletBody, true, false));
this.attachChild(bullet);
}
When i run this code the special attack body moves out of screen...I want to limit the power attack to a certain position i.e few distance away from the character.
I got the solution,I used onUpdate method and within that onupdate method i set the code as invisible,here's my code :)
public void powerattack() {
float startBulletX = player.getX() + 30;
float startBulletY = player.getY();
final Sprite ray = new Sprite(startBulletX, startBulletY,
resourcesManager.special_attack, vbom);
final Vector2 velocity = Vector2Pool.obtain(20f, 0);
final FixtureDef rayFixtureDef1 = PhysicsFactory.createFixtureDef(0, 0,
0, false, CATEGORYBIT_RAY, MASKBIT_RAY, (short) 0);
this.mRayBody = PhysicsFactory.createBoxBody(physicsWorld, ray,
BodyType.DynamicBody, rayFixtureDef1);
this.mRayBody.setLinearVelocity(velocity);
Vector2Pool.recycle(velocity);
this.physicsWorld.registerPhysicsConnector(new PhysicsConnector(ray,
this.mRayBody, true, false) {
/*Update method keeps checking whether the power attack reached the specific distance*/
#Override
public void onUpdate(float pSecondsElapsed) {
if (ray.getX() >= (player.getX() + 300)) {
ray.setVisible(false);
ray.setIgnoreUpdate(false);
}
super.onUpdate(pSecondsElapsed);
camera.onUpdate(0.1f);
}
});
mRayBody.setUserData("power");
this.attachChild(ray);
}