Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio representing anonymous inner class

I created a brand new Android application in Android Studio 0.3.6 with a LoginActivity.java that was created for me. When I view the onCreate function I see the following code:

enter image description here

But when I click on the highlighted (view)-> { code Android Studio displays what I would have expected to see:

findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        attemptLogin();
    }
});

My questions

  1. What is this called?
  2. Why does Android Studio do this?
  3. Is this something I can take advantage of since it is much less typing?
like image 604
Joe Avatar asked Nov 24 '13 17:11

Joe


People also ask

How do you use an anonymous inner class?

An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class. Tip: Anonymous inner classes are useful in writing implementation classes for listener interfaces in graphics programming.

What is anonymous inner class in Android?

An anonymous inner class is an inner class which is declared without any class name at all. In other words, a nameless inner class is called an anonymous inner class. Since it does not have a name, it cannot have a constructor because we know that a constructor name is the same as the class name.

Can inner class instantiate anonymously?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.


1 Answers

It's doing code folding similar to Java 8 lambda expressions (see the docs) even if your code isn't actually compiled with Java 8; it's just a convenience for a more compact display.

If you want to use them yourself, you can use Android Studio with Java 1.7 as a compile language, but you'll need to be using build tools v19 or later, and if you use certain language features, it will only run on phones with Kit Kat or later. Lambda functions won't get you into trouble, though.

like image 67
Scott Barta Avatar answered Sep 28 '22 00:09

Scott Barta