Results 1 to 3 of 3
  1. #1
    Jutorn's Avatar
    Join Date
    Mar 2019
    Gender
    male
    Location
    Duluth, GE
    Posts
    1
    Reputation
    10
    Thanks
    0

    Java programming technic question

    I was ready some Android codes, then I saw this:
    findViewById(R.id.myButton).setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    // Do stuff
    }
    });
    I just don't understand how you can have onClick(View v) inside
    public void onClick(View v) {
    // Do stuff
    }
    because to me findViewById(R.id.myButton).setOnClickListener(new View.OnClickListener() {

    }); is a method, how can one have one method inside an other ?
    I am aware that one can call a method inside another, this is not the case, or I am wrong.
    So i am confused by this.

  2. #2
    zephyrsin's Avatar
    Join Date
    May 2010
    Gender
    male
    Posts
    19
    Reputation
    10
    Thanks
    2
    My Mood
    Cheerful
    The code you posted can be rewritten as such

    OnClickerListener newListener = new View.OnClickListener() {
    public void onClick(View v) {
    // Do stuff
    }
    }

    findViewById(R.id.myButton).setOnClickListener(new Listener);

    From my understanding, (and this is where yours and my definition of a method might differ), this is not a method inside another method.

    What is happening is a new OnClickerListener object is being instantiated, containing a method called onClick. However, this object is also being set as the OnClickListener for findViewById(R.id.myButton) View object as well.

    Hope this helps.
    Last edited by zephyrsin; 03-23-2019 at 03:28 AM.

  3. #3
    Bababam's Avatar
    Join Date
    Nov 2020
    Gender
    female
    Posts
    6
    Reputation
    10
    Thanks
    1
    It�s a method declared on an inner class which is a way of faking a closure in java

Similar Threads

  1. INFIX TO POSTFIX JAVA PROGRAMMING[HELP]
    By zepolzirk in forum Java
    Replies: 1
    Last Post: 01-14-2012, 04:56 PM
  2. [Solved] Making a program+donate question
    By slovenc10 in forum Suggestions, Requests & General Help
    Replies: 2
    Last Post: 01-02-2012, 10:37 AM
  3. Learning C++ and Java Programming
    By MyLazySundays in forum Combat Arms Coding Help & Discussion
    Replies: 3
    Last Post: 10-18-2011, 05:10 PM
  4. a good java program
    By snipelock in forum Java
    Replies: 18
    Last Post: 04-17-2009, 02:56 PM