我已经断断续续地学习Android编程几周了,我正在尝试做一些看起来很简单的东西,但我认为我错过了什么。
我想要做的是让背景从白色平滑过渡到黑色。
我已经尝试了一些方法,但都没有成功。
我首先使用了一个for循环和LinearLayout的setBackgroundColor方法,一起从0到255改变R、G和B值。但它不起作用。
我可以进行单个设置更改,但当我循环时,只得到最后一个值。我认为发生的事情是UI在循环进行时被锁定,在循环结束时解锁。我已经尝试在循环中放置延迟(丑陋的嵌套循环延迟和Thread.sleep),但都无济于事。
有人能给我指点如何使其工作吗?我需要第二个线程来对颜色进行更改吗?我对线程有一个模糊的概念,虽然我从未使用过。
我的示例代码大致显示了我要做的事情:
main.xml是:
<?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>
我的 Java 代码为(0.01 的增量只是为了作为一个丑陋的延迟机制,以尝试缓慢地观察颜色变化):
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 the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
screen = (LinearLayout) findViewById(R.id.screen);
for (int i = 0; i < 65535; i+=0.01) {
screen.setBackgroundColor(0xff000000 + i);
}
}
}
非常感谢任何帮助。
谢谢!
Steve