tags:

views:

81

answers:

2

Is this code instantiating a SectionedAdapter object and overriding getHeaderView in one line?

SectionedAdapter tagSectionedAdapter=new SectionedAdapter() {
    protected View getHeaderView(String caption, int index,
                                    View convertView,
                                    ViewGroup parent) {
        TextView result=(TextView)convertView;

        if (convertView==null) {
            result=(TextView)getLayoutInflater()
            .inflate(R.layout.tag_listview_header, null);
        }

        result.setText(caption);

        return(result);
    }
};
+3  A: 

Yes, you're right. This is called an anonymous inner class. The class is defined but never given a name. (SectionedAdapter is actually the supertype of the anonymous class.)

Mike Daniels
+2  A: 

It's declaring a class and overriding a method.

It's similar to declaring a class like this:

class MySectionedAdapter extends SectionedAdapter
{
   @Override
   protected View getHeaderView(...)
   {
      ...
   }
}

And then instantiating that class:

SectionedAdapter tagSectionedAdapter = new MySectionedAdapter();

It's an anonymous inner class -- no name and a slightly different syntax. It's used when you need only one specific instance of a class in certain situations. For example, comparator classes are often implemented this way and passed into sort functions.

The class you implement can actually be an interface, not a class at all, as in the case of Runnable.

Jonathon