나는 일반적으로 안드로이드와 스레딩을 처음 사용합니다. 현재 UI에서 별도의 스레드에서 렌더링 및 논리가 발생하는 게임을 만들고 있습니다. 제 문제는 작업자 스레드의 게시물을 사용하여 UI를 업데이트 할 수 없다는 것입니다.게시물 문제를 사용하여 게시물
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 스레드에서 실행해야합니다 이것은 실행 가능한 구현하는 클래스가
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();
}
:
이
내 mainActivity입니다 권리? 하지만 텍스트를 설정하려고 할 때 null 개체 참조가 나타납니다. 그리고 예 id가 fps_counter 인 텍스트가 있습니다.
는 UI 스레드에서 코드를 실행하는 runOnUiThread를 사용해보십시오. – Fustigador
레이아웃 xml을 게시하십시오. – TpoM6oH
어디에서 불러야합니까? @Fustigador – Tagor