Listener in Android

The observer pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

The object which is being watched is called the subject.The objects which are watching the state changes are calledobservers or listeners.

How to make in android is the same that in java.

The first

1) To Create a class which name is MyListener.
-Interface.
-Variable (listener).
-Void.
-To call the void if (listener!= null).

package com.thedeveloperworldisyours.simplelistener;

public class MyListener {
	public interface Listener {
        public void onStateChange(boolean state);
    }

    private Listener mListener = null;
    public void registerListener (Listener listener) {
        mListener = listener;
    }

    private boolean myBoolean = false;
    public void doYourWork() {
    	myBoolean = true;
        if (mListener != null)
            mListener.onStateChange(myBoolean);
    }
}

The second
2)To use the listener
-Declare the variable
-new Listener
-to use the listener’s void

package com.thedeveloperworldisyours.simplelistener;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;

public class TheDeveloperWorldIsYours extends Activity implements MyListener.Listener{

	private TextView mTextView;
	private MyListener mListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_the_developer_world_is_yours);

		mTextView = (TextView) findViewById(R.id.tvTheDeveloperWorldIsYours);
		mListener = new MyListener();
		mListener.registerListener(this);
		mListener.doYourWork();
	}
	@Override
	public void onStateChange(boolean state) {

		if (state) {
			mTextView.setText("on");
        } else {
        	mTextView.setText("off");
        }

	}

}

Download the example here

One thought on “Listener in Android

Leave a Reply

Your email address will not be published. Required fields are marked *