Getting the context inside a custom view?

16,272

The view has a method to get the context. See the android API for getContext().

Share:
16,272

Related videos on Youtube

soren.qvist
Author by

soren.qvist

Updated on June 04, 2022

Comments

  • soren.qvist
    soren.qvist almost 2 years

    I have made a small custom view component:

    public class ActionBar extends RelativeLayout
    {
    
        public ActionBar(Context context, AttributeSet attrs)
        {
            super(context, attrs);
    
            // .. custom logic here
        }
    
        private class homeButtonListener implements OnClickListener
        {
    
            @Override
            public void onClick(View v)
            {
                // how do i get the context here?
            }
    
        }
    
    }
    

    Every ActionBar component comes with a home-button, so I thought it would be appropriate to put it's onClickListener inside the view definition itself. The button should return the user to the main activity when clicked, but I need a Context in order to start activities. Can I create a local reference to the context passed in the constructor, without running into a mess of memory leaks?

  • soren.qvist
    soren.qvist over 12 years
    Thanks! Sometimes the answer is just staring you in the face.