[英]How to change a background image?
I studied all possible answers and found something that should work: 我研究了所有可能的答案,并发现了一些可行的方法:
int[] tabelazdjec={R.drawable.pic2,R.drawable.pic3};
LinearLayout mylay=(LinearLayout)findViewById(R.id.mylay);
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.yess);
Thread timer = new Thread(){
public void run()
{
for(int i=0;i<tabelazdjec.length;i++)
{
try
{
mylay.setBackgroundResource(tabelazdjec[i]);
sleep(500);
}
catch(Exception e)
{
e.printStackTrace();
}
}}
};
timer.start();
It doesn't. 没有。 The error appears in the second line where I declare the LinearLayout variable.
错误出现在我声明LinearLayout变量的第二行。 If I move the declaration into try{}catch{} part, the app runs but try{} doesn't execute, so it is quite certainly this exact line.
如果将声明移到try {} catch {}部分中,则该应用程序将运行,但try {}无法执行,因此可以肯定地是这行。 The xml file goes as follows:
xml文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/mylay"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/pic1" >
</LinearLayout>
Sorry if the question seems trivial, i've spent last few hours staring at that line and can't find anything wrong with it. 抱歉,如果这个问题看起来很琐碎,我已经花了几个小时盯着那条线,找不到任何问题。 Maybe I'm blind...
也许我是瞎子
You can't initialize a View
until you have inflated its layout
. 扩大
View
的layout
之前,您无法初始化View
。 Move the LinearLayout
initialization to below setContentView()
将
LinearLayout
初始化移动到setContentView()
下面
LinearLayout mylay;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.yess);
mylay=(LinearLayout)findViewById(R.id.mylay);
Thread timer = new Thread(){
Your Views
will return null
if you try to initialize them before inflating the layout
that they belong to as with setContentView()
. 如果您在使用
setContentView()
夸大它们所属的layout
之前尝试初始化它们,则Views
将返回null
。
Also, as E.Odebugg has pointed out in a comment, you are trying to update a UI
element in a background Thread
which will be your next problem. 另外,正如E.Odebugg在评论中指出的那样,您正在尝试在后台
Thread
更新UI
元素,这将是您的下一个问题。 You need to use runOnUiThread()
to update the UI
. 您需要使用
runOnUiThread()
来更新UI
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.