Feb 4, 2013

Implement callback method

In this example, demonstrate how to implement callback method in Android. The main activity implements interface of callback method, and register itself as the interface to sub-class. When a button in main activity clicked, it call a method in sub-class, then call the callback method in main activity.

SubClass.java
package com.example.androidcallback;

public class SubClass {
 
 interface MyCallbackClass{
        void callbackReturn();
    }
 
 MyCallbackClass myCallbackClass;
 
 void registerCallback(MyCallbackClass callbackClass){
  myCallbackClass = callbackClass;
 }

 void doSomething(){
  //do something here
  
  //call callback method
  myCallbackClass.callbackReturn();
 }

}


MainActivity.java
package com.example.androidcallback;

import com.example.androidcallback.SubClass.MyCallbackClass;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements MyCallbackClass{
 
 Button buttonCallSubClass;
 TextView textResult;
 SubClass mySubClass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonCallSubClass = (Button)findViewById(R.id.callsubclass);
        textResult = (TextView)findViewById(R.id.result);
        
        mySubClass = new SubClass();
        
        mySubClass.registerCallback(this);
        
        buttonCallSubClass.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    mySubClass.doSomething();
   }});
    }

 @Override
 public void callbackReturn() {
  textResult.setText("Callback function called");
 }
   
}


layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:id="@+id/callsubclass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Call sub-class" />
    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


Implement callback method

No comments:

Post a Comment

Infolinks In Text Ads