Ilja KO
Ilja KO

Reputation: 1616

How does Android's setOnCLickListener() works?

I wonder how Android OnClik Listener works? What Pattern is it? Observer?

I cant imagine how I can Implement it in my App! It needs to be a custom implementation because I want to do it with my Objects not with views.

So how can I achieve to call obj.setOnClickListener(new Class(){});

in my code?

I mean ok I could have a methode in my baseclass from which the derived classes implement and then just havin a static ArrayList or so. But how can I add new Classes to this List at runtime?

The definiton of this class OnClickListener(){} is strange.

How is it possible to define an existing class and overriding a method?

My Java is not that good never done this...

EDIT: THIS QUESTION IS NOT ABOUT HOW TO USE ONCLICKLISTENER. I KNOW HOW TO USE THAT...

What i want:

I want a Super Class having an implementation of a method like this:

public void setMyOnclickListener(MyOnClickListener myListener)
{
    //magic code
}

and now I want to have an Object of this class lets call it

Subclass obj;

and now I want to do this:

obj.setMyOnClickLister(new MyOnClickListener()
    {
        //defined method at runtime
        public void aDefinedMethod()
        {
            //here goes in some code
        }
    });

how can I have a method with a class as a parameter which only exist as an anonymous class?

EDIT2:

Ok I get it OnClickListener is just an Interface -.- not a class defintion That was my confusion!!!

Upvotes: 2

Views: 3289

Answers (4)

Sergey Shustikov
Sergey Shustikov

Reputation: 15831

Each View contains ListenerInfo static class which holds callbacks, OnClickListener too actually.

How it works?

System always holds all views on screen. When user tap on screen we have a recursive foreach cycle :

switch(event) {
    ...
    case ON_CLICK:
    process(ViewRoot);
}

void process(View view) {
    
    for(View view : view.getChilds()) {
        if(view instanceOf ViewGroup && ((ViewGroup)view).getChildCount() > 0) {
             process(view);
        }
        if(view.getListenerInfo().mOnClickListener != null)
             view.getListenerInfo().mOnClickListener.onClick(view)
    }
}

When you call setOnClickListener you actually say "hey Android! here it callback. And when user make click, please use it."

View.class also have getListenerInfo method which returns ListenerInfo object.

System use this method to dispatch events.

So no Observer pattern here. It just simple check of existing callback.

Upvotes: 7

R. Suntjens
R. Suntjens

Reputation: 121

you need to initialize your object (button) first

public class SomeActivity {
  ...
  private Button subButton1, subButton2;
  ...

  protected void onCreate(Bundle savedInstanceState) {
    ...
    init();
  }

  private void init() {
        subButton1 = (Subclass) findViewById(R.id.home_button1);
        subButton2 = (Subclass) findViewById(R.id.home_button2);
  }

// next is the onClickListener

  private void init() {
    ...
        subButton1.setOnClickListener(new MyOnClickListener() {
            @Override
            public void myOnClick(View v) {
                System.out.println("Your own on click 1");
                Toast.makeText(HomeActivity.this, "Your own on click 1", Toast.LENGTH_SHORT).show();
            }
        });
        subButton2.setOnClickListener(new MyOnClickListener() {
            @Override
            public void myOnClick(View v) {
                System.out.println("Your own on click 2");
                Toast.makeText(HomeActivity.this, "Your own on click 2", Toast.LENGTH_SHORT).show();
            }
        });
  }

  private void methodCall() {
    // some more code...
  }

// Subclass

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

/**
 * Created by roelsuntjens on 01-10-15.
 */
public class Subclass extends Button {
    public Subclass(Context context) {
        super(context);
    }

    public Subclass(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public Subclass(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public Subclass(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public void setOnClickListener(MyOnClickListener l) {
        super.setOnClickListener(l);
    }

    @Override
    public void setOnClickListener(OnClickListener l) {
        super.setOnClickListener(l);
    }
}

// MyOnClickListener

import android.view.View;

/**
 * Created by roelsuntjens on 01-10-15.
 */
public abstract class MyOnClickListener implements View.OnClickListener {
    public MyOnClickListener() {
    }

    public abstract void myOnClick(View v);

    @Override
    public void onClick(View v) {
        myOnClick(v);
    }
}

// In XML I used this:

        <View3D.Subclass
            android:id="@+id/home_button1"
            android:layout_width="match_parent"
            android:text="Button1"
            android:layout_height="wrap_content" />
        <View3D.Subclass
            android:id="@+id/home_button2"
            android:layout_width="match_parent"
            android:text="Button2"
            android:layout_height="wrap_content" />

Upvotes: 0

user3507451
user3507451

Reputation: 39

It's very easy...just in your activity_main.xml layout create a button like this

          <Button
    android:id="@+id/btnTake"
    android:layout_width="wrap_content"
//  android:onClick="onClick" (It will automatically create the method if u use onclic)//
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
     />

Now just call the button with its id(IF u r not writing android:onClick="onClick" )

now in Main Activity do this

      protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     btnTack = (Button) findViewById(R.id.btnTakePic);
     btnTack.setOnClickListener(this);

//call intent or do what u want

Now do what ever you want to do..

Upvotes: -1

Jean-baptiste Valero
Jean-baptiste Valero

Reputation: 81

You can implement onClickListener like that by implementing interface OnClickListener. Set to your button on setOnClickListner(this) in your activity will listening the click event on the onClick method.

You can also create your on listener by declaring a private OnClickListener like that :

private OnClickListener listener = new OnClickListener() {
    @Override
    public void onClick(View view) {
        // Click occurs, do something
    }
};

Then set button.setOnClickListener(listener);

Upvotes: -1

Related Questions