gpt4 book ai didi

java - 使用帖子的线程问题

转载 作者:行者123 更新时间:2023-12-01 20:06:47 26 4
gpt4 key购买 nike

我对 Android 和线程总体来说是新手。我目前正在制作一款游戏,其中渲染和逻辑发生在与 UI 不同的线程上。我的问题是我似乎无法使用工作线程中的帖子更新用户界面。

这是我的主要 Activity :

private GameScene gameScene;
private Handler uiHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.game);
uiHandler = new Handler(Looper.getMainLooper());

gameScene = new GameScene(getApplicationContext(), uiHandler);
LinearLayout gameHolder = (LinearLayout)findViewById(R.id.game_view);
gameHolder.addView(gameScene);
gameScene.resume();
}

这是实现 runnable 的类:

public abstract class Scene extends SurfaceView implements Runnable {

Handler uiHandler;
Thread thread = null;
public Scene(Context context, Handler uiHandler) {
super(context);
this.uiHandler = uiHandler;
}

@Override
public void run() {
uiHandler.post(() -> {
TextView textView = findViewById(R.id.fps_counter);
textView.setText("hello");
});
}

public void resume() {
thread = new Thread(this);
thread.start();
}

xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
android:id="@+id/game_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:visibility="visible">

<TextView
android:id="@+id/fps_counter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="0"
android:textColor="@color/colorAccent"
android:textSize="24sp" />
</LinearLayout>

</FrameLayout>

post里面的代码应该在ui线程上运行,对吗?但是当我尝试设置文本时,我得到了一个空对象引用。是的,ID 为 fps_counter 的文本存在。

最佳答案

由于 Gamescene 不包含 fps_counter TextView ,因此请修改抽象场景和类扩展,以便可以传递对 TextView 的引用。

public abstract class Scene extends SurfaceView implements Runnable {

Handler uiHandler;
Thread thread = null;
TextView textView;
public Scene(Context context, Handler uiHandler, TextView textView) {
super(context);
this.uiHandler = uiHandler;
this.textView = textView;
}

@Override
public void run() {
uiHandler.post(() -> {
textView.setText("hello");
});
}

public void resume() {
thread = new Thread(this);
thread.start();
}

然后使用 TextView 的第三个参数创建 GameScene :

TextView textView = findViewById(R.id.fps_counter);
// no need to use getApplicationContext(), you may use this (a reference to "mainActivity")
gameScene = new GameScene(this, uiHandler, textView);

关于java - 使用帖子的线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47334085/

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