私はアンドロイドとスレッド一般的に新しいです。私は現在、UIとは別のスレッド上でレンダリングとロジックが発生するゲームを作っています。 私の問題は、ワーカースレッドから投稿を使用してUIを更新するように見えることです。投稿スレッドを使用して投稿
これは私のmainActivityです:
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();
}
これは、実行可能な実装するクラスです:
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>
コードがUIスレッド上で実行する必要があります右?しかし、私はテキストを設定しようとすると、nullオブジェクト参照を取得しています。はい、id fps_counterのテキストが存在します。
:
は、その後のTextViewの3番目のパラメータでGameSceneを作成します。 – Fustigador
あなたのレイアウトxmlを投稿してください。 – TpoM6oH
どこで呼びますか? @Fustigador – Tagor