gpt4 book ai didi

android - 自定义 SurfaceView 和默认 android View 之间的通信

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:52:45 25 4
gpt4 key购买 nike

我的问题是自定义 GameView(扩展 SurfaceView)和 TextView 之间的通信:我想从 GameView 内部设置 TextView 的文本。在主要 Activity 中,我正在使用这个布局文件,它应该解释我的应用程序的结构:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#00ff00"
>
<TextView
android:id="@+id/scoreTV"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="score: 0"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back"
android:layout_alignParentRight="true" />
</RelativeLayout>
<org.gk.grApp.GameView
android:id="@+id/gameplayScreen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>

我无法在我的 GameView 对象中更改 TextView 的文本,因为不可能从另一个接触 UI 线程。处理程序也不起作用,因为我无法提供处理程序对 GameView 构造函数的引用,这是在加载此 xml 文件后执行的(阅读有关 xml 文件的默认构造函数的信息,例如此处 How can I use GLSurfaceView in a LinearLayout together with other Views, such as TextView or Button? )。你知道我现在应该做什么吗?也许我的推论是错误的,所以请告诉我这一点。

编辑:我更改了我的 xml 文件,而不是我现在拥有的 GameView:

<LinearLayout
android:id="@+id/gameplayScreen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</LinearLayout>

我还在构造函数的签名中添加了一个参数(第三个):

public GameView(Context context, AttributeSet as, Handler h) { ... } 

并在 GameplayActivity 中更改了我的 onCreate:

protected void onCreate(Bundle savedInstanceState) {        
super.onCreate(savedInstanceState);
setContentView(R.layout.gameplay);

LinearLayout ll = (LinearLayout)findViewById(R.id.gameplayScreen);
GV = new GameView(this, null, scoreHandler);
ll.addView(GV);
}

它起作用了,现在我可以设置 TextView 的文本了,但是在单击后退按钮后又抛出了另一个异常:“暂停未恢复的 Activity :{org.gk.grApp/org.gk.grApp.MainMenuActivity}”。我刚开始搜索这方面的信息。

最佳答案

首先在 Activity 级别引用TextView:

TextView txv;

在 onCreate 中分配这个引用:

txv = (TextView) findViewById(R.id.MyTextView);

然后像这样在 onCreate 之后在你的 Activity 中创建一个方法:

public void setTextView(final String txt){
MyActivity.this.runOnUiThread(new Runnable() {
public void run() {
txv.setText(txt);
}
});
}

然后从自定义 View 中调用:

((MyActivity) getContext()).setTextView(str);

关于android - 自定义 SurfaceView 和默认 android View 之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8685201/

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