In Android, how do I smoothly fade the background from one color to another? (How to use threads) -
i've been playing android programming on , off couple of weeks, , i'm trying work seems simple, think missing something.
what trying have background fade from, say, white black smoothly.
i've tried few things, none of seem work.
the first thing did using loop , setbackgroundcolor method linearlayout, changing r, g, , b values 0 255. doesn't work.
i can one-of settings changes, when loop nothing last value. think happening ui locking while loop in progress , unfreezing when loop ends. i've tried putting delays in loop (ugly nested loop delays , thread.sleep), no avail.
can give me pointers how working? need second thread change color? i've got vague idea of threads, although have never used them.
my sample code showing trying follows:
main.xml is:
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/screen" > <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </linearlayout>
and java code (the 0.01 inc. act ugly delay mechanism try see viewing of colors change slowly):
package nz.co.et.bgfader; import android.app.activity; import android.os.bundle; import android.widget.linearlayout; public class bgfader extends activity { linearlayout screen; /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); screen = (linearlayout) findviewbyid(r.id.screen); (int = 0; < 65535; i+=0.01) { screen.setbackgroundcolor(0xff000000 + i); } } }
any appreciated
cheers
steve
in loop, setting on background fast ui not (will not) able schedule update of display. yes, better use second thread update background or else stall ui thread. try following:
linearlayout screen; handler handler = new handler(); @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); screen = (linearlayout) findviewbyid(r.id.screen); (new thread(){ @override public void run(){ for(int i=0; i<255; i++){ handler.post(new runnable(){ public void run(){ screen.setbackgroundcolor(color.argb(255, i, i, i)); } }); // next pause thread time try{ sleep(10); } catch{ break; } } } }).start(); }
this threaded version of code.
Comments
Post a Comment