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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.