Move image up they y-axis in eclipse - java

I am making a game for androids using eclipse and I had some trouble trying to figure this out. I already have 2 images on my layout and I just want to figure out how to make them move one unit up the y axis with a timer that is repeatedly. Thanks alot for any help appreciate it!

You can do something like
final int interval = 1000; // one second
View myView = ...;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// Do work
myView.setY(myView.getY() + 1);
handler.postDelayed(this, interval);
}
handler.post(runnable);

Related

I need someone to explain for me this java code

I'm solving an exercise for my university and there is this code in my pdf that my supposed to use to delay the change of the colour of the text on a button, i don't understand how it exactly works so please can someone explain it
HandlerThread handlerThread = new HandlerThread("showText");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
Runnable runnable = new Runnable() {
int i = 0;
#Override
public void run() {
i++;
handler.postDelayed(this, 1000);
if (i > 1)
button.setTextColor(getResources().getColor(android.R.color.transparent));
}
};
handler.post(runnable);
This code is in obscure way causing that Runnable to be called with the delay of 1s (every second) because it reschedules itself each time. The int i is guarding button.setTextColor from executing the first the.
This code is however very messy, the way it should be done is as follows:
Runnable runnable = new Runnable() {
#Override
public void run() {
button.setTextColor(getResources().getColor(android.R.color.transparent));
}
};
handler.postDelayed(runnable, 1000);
or with lambda expression just as following:
handler.postDelayed(() -> button.setTextColor(getResources().getColor(android.R.color.transparent)), 1000);

Andengine TimerHandler and detecting collisions

I'm developing a game where LittleMan can move from block to block, and certain blocks are moving. I'm trying to detect when he moves to a new moving block, if that block is beneath him or if it has moved. I'm using Andengine's TimerHandler to check every 0.1 seconds but it is not working. Here's the code:
private void OnMovingBlock(final int CurrentPosRow, final int CurrentPosColumn) {
this.getEngine().registerUpdateHandler(new TimerHandler(0.1f, true, new ITimerCallback() {
#Override
public void onTimePassed(final TimerHandler pTimerHandler) {
if (LittleManPos[0] == CurrentPosRow && LittleManPos[1] == CurrentPosColumn) {
if (!LittleMan.collidesWith(MapRectangles[CurrentPosRow][CurrentPosColumn])) {
RestartScene();
}
}
}
}));
}
It seems he can move to the block and sit there with it moving in and out beneath him but it doesn't call RestartScene() UNTIL I move him again. Any idea where I am going wrong? Or is there another way to do this?
Why don't create a Timer?
TimerTask task = new TimerTask(){
#Override
public void run(){
// your code goes here
}
};
Timer timer = new Timer();
timer.sechedule(task, 0, 100); // 100 --> 0.1 second
To cancel the Timer, call timer.cancel();.

How to cycle through background colors in Android / Java?

I have a list of hex colors with a duration in milliseconds for each one. I would like to fill the screen with each color for its duration, then move on to the next color.
I tried to iterate over the colors to do the following:
myView.setBackgroundColor(Color.parseColor( theColor ));
SystemClock.sleep( theDuration );
myView.setBackgroundColor(Color.parseColor( nextColor ));
SystemClock.sleep( nextDuration );
etc...
which seemed obvious to me but doesn't do anything to the view when it's running, at least in my AVD. I'm learning that it's because Android only draws at predefined times. (I tried calling "Invalidate()" as well with no luck.)
What is the best way to display all the colors consecutively?
(I realize I shouldn't be calling sleep() either, so any suggestions for that would also be appreciated.)
Thanks.
new Thread() {
#Override
public void run() {
YourActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
myView.setBackgroundColor(Color.parseColor( theColor ));
}
Thread.sleep( theDuration);
YourActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
myView.setBackgroundColor(Color.parseColor( nextColor ));
}
Thread.sleep( nextDuration );
}
}.start();
Put this in a method and call it.
There are many ways to achieve what you want. One could be to use Handler and Runnable. Assuming you know how to get current color and duration, you could do:
declare Runnable as class variable
private Runnable runnable = null;
inside onCreate(), after you set initial view, initialise Handler
final Handler handler = new Handler();
initialise runnable and change the background in run() method
runnable = new Runnable() {
#Override
public void run() {
//change the color
myView.setBackgroundColor(currentColor);
//run it again in nextDuration miliseconds
handler.postDelayed(toggle, nextDuration);
}
};
//start runnable in theDuration miliseconds
handler.postDelayed(toggle, theDuration);
You could have arrays of colors and durations and cycle through them with index variable. This is assuming that myView is a valid view.
EDIT:
To those who downvoted, read the documentation for Handler:
When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it...
In other words, you are creating a handler in onCreate() of your activity, so it will be able to update your view.
This blogpost from adroid-developers website uses very similar construct as proposed above.
The Handler runs the update code as a part of your main thread, avoiding the overhead of a second thread and also making for easy access to the View hierarchy used for the user interface.
See here and here answered by CommonsWare and here - answered by Laith Alnagem.
I ended up creating a Runnable inside the my button click event handler. Everything (looping through the colors and durations plus "sleeping" based on the durations) is done in the Runnable run() method.
public void playOnClick(View v) {
Runnable runnable = new Runnable() {
public void run() {
...
}
Then I created a handler inside my UI Activity class that just changes the color of the background.
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
String theColor = b.getString("color");
myView = (View) findViewById(R.id.bigView);
myView.setBackgroundColor(Color.parseColor(theColor));
}
};
Inside the run() method, he Runnable sends a message to the handler containing the background color using Bundle/Message objects:
b = new Bundle();
b.putString("color", theColor);
msg = new Message();
msg.setData(b);
handler.sendMessage(msg);

Using a counter inside a java.util.Timer in Android Activity causes app to crash

I'd like to accomplish something which I would think to be simple, but is turning out to be a hassle.
I have a loading screen with a picture, and I'd like for it to fade in and out as the application is loading. I decided to accomplish this by changing it's opacity frequently relative to the sine value of a counter. My code is as follows:
ImageView loadingRaven; //loading raven at the start of the app
Timer timer; //timer that we're gonna have to use
int elapsed = 0; //elapsed time so far
/*
* the following is in the onCreate() method after the ContentView has been set
*/
loadingRaven = (ImageView)findViewById(R.id.imageView1);
//fade the raven in and out
TimerTask task = new TimerTask()
{
public void run()
{
elapsed++;
//this line causes the app to fail
loadingRaven.setAlpha((float)(Math.sin(elapsed)+1)/2);
}
};
timer = new Timer();
timer.scheduleAtFixedRate(task, 0, 50);
What is the problem that's causing my program to fail? Am I correctly using Timer and TimerTask? Or is there perhaps a better way to update the opacity of the image frequently so it eases in and out smoothly?
Thanks
TimerTask runs on a different thread. So update ui on the main ui thread. Use runonuithread
TimerTask task = new TimerTask()
{
public void run()
{
elapsed++;
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
loadingRaven.setAlpha((float)(Math.sin(elapsed)+1)/2)
}
});
}
};
TimerTask runs on a different thread. You can use Handler and postDelayed as suggested by
pskink

Android Progress bars losing their value when updated in a Handler

I am working on an Android app that displays cell phone usage information in a progress bar. The bar changes color based on the amount of usage from green to yellow to red. When my TimerTask executes the update though (via a Handler so it goes through the UI thread and not the Timer thread), the progress bars empty, even though the text labels are updated correctly. The code updating the progress bar is:
private void SetBarColor(ProgressBar bar, int progress, int secondaryAdditive){
int setTo = R.drawable.greenbar;
if(progress < 60)
setTo = R.drawable.greenbar;
else if (progress < 90)
setTo = R.drawable.yellowbar;
else
setTo = setTo = R.drawable.redbar;
bar.setProgress(progress);
bar.setSecondaryProgress(progress + secondaryAdditive); //Mocking up phone usage
Rect bounds = bar.getProgressDrawable().getBounds();
bar.setProgressDrawable(this.getResources().getDrawable(setTo));
bar.getProgressDrawable().setBounds(bounds);
bar.setVisibility(View.VISIBLE);
}
This method works fine when called the first time in the onCreate method, but when called from the TimerTask, the bars simply hide themselves, showing only the grey background (as if their progress == 0). I've used the debugger and confirmed that the right values are going into the setProgress and setSecondaryProgress() calls. I have also tried setting the progress both before (as in the snippet above) and after the setProgressDrawable call, to no avail.
Anyone run into something like this?
EDIT: By request, some additional code. Here's the Runnable:
private class MyTime extends TimerTask {
#Override
public void run() {
ReQueryCount--;
if(ReQueryCount <= 0){
ReQueryCount = ReQueryCountStarter;
HeartbeatHandler.post(new Runnable() {
public void run() {
GetDataFromServer();
}
});
}
}
}
The HeartbeatHandler is created in onCreate.
GetDataFromServer gets some data from server, but the part that consumes my SetBarColor above is:
private void UpdateProgressBars(ServiceHelper.UsageResult result) {
int voiceBarProg = (int)((double)result.VoiceUsage / (double)result.MaxVoice * 100);
int dataBarProg = (int)((double)result.DataUsage / (double)result.MaxData * 100);
int msgBarProg = (int)((double)result.TextUsage / (double)result.MaxText * 100);
SetBarColor(voiceBar, voiceBarProg, PhoneVoice);
SetBarColor(dataBar, dataBarProg, PhoneData);
SetBarColor(msgBar, msgBarProg, PhoneText);
}
Short of posting the layouts, manifest and the rest I'm not sure what other code would be helpful.
After searching for hours for a solution of this problem I have found this article that has an answer that has helped me.
But in addition to the answer there I have also get/set the drawable bounds too. So I have a custom ProgressBar which has the following method to set progress color and amount:
public void setProgressColorAndFill(int color, int fill){
Drawable bgDrawable = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{0xFFdadada, 0xFFdadada});
Drawable proDrawable = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{color, color});
ClipDrawable clip = new ClipDrawable(proDrawable, Gravity.LEFT,ClipDrawable.HORIZONTAL);
Drawable[] layers = new Drawable[2];
layers[0] = bgDrawable;
layers[1] = clip;
LayerDrawable layerDrawable = new LayerDrawable(layers);
layerDrawable.setId(0, android.R.id.background);
layerDrawable.setId(1, android.R.id.progress);
Rect bounds = ((LayerDrawable)getProgressDrawable()).getBounds();
setProgressDrawable(layerDrawable);
getProgressDrawable().setBounds(bounds);
setProgress(1);
setMax(100);
setProgress(fill);
}
Hope this will be useful to someone.

Categories

Resources