stefan
stefan

Reputation: 10355

Custom view updating content of another view

I have the following situation: in the main file I do setContentView(R.layout.main); which looks as follows:

<?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>

the View "test.gustav.Spielfeld" refers to a class "Spielfeld" extending "View".

I now need a method that updates the content of the TextView with id "result" if a something happens in the onTouchEvent(..)-method in the Spielfeld-View.

How to do this? I've tried making a public TextView in the Main-Class but the Spielfeld class won't accept Main.this.myTextView.

Upvotes: 0

Views: 1405

Answers (1)

Knickedi
Knickedi

Reputation: 8787

I would recommend a callback approach (just like android does for all events):

Create a interface which represents the callback:

public interface OnSpielfeldUpdate {

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

Provide a setter for the callback in SpielFeld (which will be used to send updates):

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

Set your callback in your activity (or somewhere else):

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

Upvotes: 4

Related Questions