2

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

7
  • how do u click if its not a view?, can u post a sample code regarding this so it will be easy to understand. Oct 1, 2015 at 10:02
  • 1
    OnClickListeners are for view, what is that you actually try to achieve Oct 1, 2015 at 10:03
  • I want to send out an signal in my list where I put my objects in, but I want like in Android to let the User of my framework to decide what action should be taken when this item is clicked. Just like normal Observer Pattern but the body of the method that should be executed by the observable should be declared when setting the listener
    – Ilja KO
    Oct 1, 2015 at 10:04
  • Also your listview has an onItemClicked method. Inside you can decide what should happen, if the user clicks on an entry.
    – Prexx
    Oct 1, 2015 at 10:06
  • -.- what listview? why are you commenting?
    – Ilja KO
    Oct 1, 2015 at 10:18

4 Answers 4

7

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.

2
  • Im gonna trust you thanks. I studied the source code also some minutes ago and also saw no Pattern. Ok I see its just another kind of structural pattern but it really looked like observer pattern, because events and listener sounds like observer
    – Ilja KO
    Oct 1, 2015 at 13:17
  • @IljaKO yes, u are right. For the first time i think same. Oct 1, 2015 at 17:33
0

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" />
1
  • youre trying to tell me how to use an onclicklistener? did you read the question?
    – Ilja KO
    Oct 1, 2015 at 10:16
-1

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);

3
  • why you want to tell me how to use an onclicklistener from androids framework? -I want my own!!!
    – Ilja KO
    Oct 1, 2015 at 10:16
  • I'm sorry... but i see that others users explain you the same thing so maybe your initial question wasn't so explicit Oct 1, 2015 at 13:44
  • its ok...i updated the question but still problem is there hwo to achieve the functionality in my class heirarchies
    – Ilja KO
    Oct 1, 2015 at 14:13
-1

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

1
  • No! Thats not what I want! I know how to inflate View I know how to set onclicklistener and I know how to do Android programming. read the question gain pls
    – Ilja KO
    Oct 1, 2015 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.