gpt4 book ai didi

java - 在线程中设置内容 View

转载 作者:行者123 更新时间:2023-11-29 05:38:59 25 4
gpt4 key购买 nike

我想制作一个线程来改变我的 Activity 布局...我有 2 种布局:welcomepage 和 activity_main ...线程的目标:当我启动我的应用程序时,欢迎页面布局将在 5 秒内可见,之后布局将再次变为 activity_main ...

我写的代码如下:

package com.example.tripolimazad;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

public TextView counter = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcomepage);
counter = (TextView) findViewById(R.id.Counter);

Thread th=new Thread(){
@Override
public void run(){
try
{
Thread.sleep(10000);
setContentView(R.layout.activity_main);
}catch (InterruptedException e) {
}
}

};
th.start();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

但是没用!!!有没有人有任何解决方案!

最佳答案

您不能在非 UI 线程上更改 UI,但是在 Activity 中,您可以使用 runOnUiThread 方法:

runOnUiThread(new Runnable() {
@Override
public void run() {
setContentView(R.layout.activity_main);
}
});

不过,在您的 onCreate 中使用它似乎很奇怪。

关于java - 在线程中设置内容 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18389971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com