Repeatedly flipping between two layout colors
I am working on an app in which I am trying to continuously flip between two colors of Layout (Linear Layout) , but the colors are not changing as expected. When I run the app, it waits and only the color mentioned the last is changed and that too only once, I suspect that the layout is not able to change the color as soon as the application is trying to change its color, as a result the app is only able to change the color once.
Below is the code
flasher.java
package com.tutorial.flasher;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
//import android.os.SystemClock;
import android.widget.开发者_StackOverflow中文版LinearLayout;
public class flasher extends Activity {
/** Called when the activity is first created. */
LinearLayout llaLayout;
int a,b = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
llaLayout = (LinearLayout)findViewById(R.id.layo);
for (int i=0;i<4;i++)
{
//SystemClock.sleep(2000);
//llaLayout.buildDrawingCache()
Thread.currentThread();
try
{
Thread.sleep(2000);
}
catch (Exception e)
{
e.notifyAll();
}
llaLayout.setBackgroundColor(Color.parseColor("#0000FF"));
//SystemClock.sleep(2000);
Thread.currentThread();
try
{
Thread.sleep(2000);
}
catch (Exception e)
{
e.notifyAll();
}
llaLayout.setBackgroundColor(Color.parseColor("#FF0000"));
// SystemClock.sleep(2000);
}
}
}
I am only getting the Red color in the layout.
Thanks, Sid
You can achieve this using Handler
.
For example:
private boolean bool = true;
llaLayout = (LinearLayout)findViewById(R.id.layo);
final Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable(){
@Override
public void run() {
mHandler.postDelayed(this, 1000);
changeColor();
}
private void changeColor() {
if (bool) {
llaLayout.setBackgroundColor(Color.RED);
bool = false;
} else {
llaLayout.setBackgroundColor(Color.BLUE);
bool = true;
}
}}, 1000);
This code will recursively call same function changeColor()
where 1000 is time in milliseconds to call it next time.
Hope it helps.
You can't block in the main thread. That will immediately make your application unresponsive.
You could use a timer or a separate thread to do this. You just need to be sure to perform the actual UI-related function (setBackgroundColor
) on the UI thread. For this, you could use Activity.runOnUiThread
.
精彩评论