2011-10-09 75 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

相關問題