2011-10-09 78 views
0

我有以下情况: 在主文件中我做了 setContentView(R.layout.main);这看起来 如下:自定义视图更新另一个视图的内容

<?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" 
android:id="@+id/layout" 
> 
<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/result" 
    android:text="Gesamtstrecke: 0.0" 
/> 
<test.gustav.Spielfeld 
    android:id="@+id/spielfeld" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 
</test.gustav.Spielfeld> 
</LinearLayout> 

查看“test.gustav.Spielfeld”是指一类“施皮尔费尔德”扩展“视图”。

我现在需要一个方法,如果在Spielfeld-View的onTouchEvent(..) - 方法中发生了某些事情,需要更新ID为“result”的TextView的内容。

如何做到这一点?我试过在Main-Class中创建一个公共TextView,但Spielfeld类将不接受Main.this.myTextView。

回答

3

我会建议回调方法(就像Android为所有事件):

创建它代表了回调接口:

public interface OnSpielfeldUpdate { 

    public void onSpielfeldUpdate(Object myEventData, ...); 
} 

提供一个设置在SpielFeld回调(这将被用来发送更新):

public void setOnSpielfeldUpdate(OnSpielfeldUpdate callback) { 
    this.callback = callback; 
} 

设置你的回调在您的活动(或其他地方):

mySpielfeld.setOnSpielfeldUpdate(new OnSpielfeldUpdate() { 
    public void onSpielfeldUpdate(Object myEventData, ...) { 
     // perform update on result view 
    } 
} 
+0

只是完美的,非常感谢! – stefan

+0

对不起,对于德语和英语单词的组合听起来很有趣,特别是对德国读者:D –

+0

是的,我知道,这是一个很糟糕的风格(硬编码不是英语)。有趣的是,我研究过的大学的一些教授曾经用例子编写过这样的代码;-) – Knickedi

相关问题