I'm so interested in getContext()
method and how it works. For example, I wrote recycleView
@Override
public RecycleView.ViewHolder onCreateViewHolder(ViewGroup parent ,int viewtype)
{
View view =LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);}
and I call it on my fragment class defined to MainActivity
.
My question here how does getContext()
method return MainActivity
? How does getContext()
is understood?
I look at that method into the Android Studio, but I didn't understand it as well.
For the ultimate reference: Context | Android Developers
Long story short, the View
class, and thus all of it's subclasses (like ViewGroup
), have a defined function called getContext()
which returns a Context
object. This class is abstract and the implementation is provided by the Android system, which is why the actual functionality is not easy to understand. It allows you to access global information about an application's environment, such as themes, resources, etc. It is pretty magical, but that magical aspect can be costly if you aren't careful. It is very easy to leak a Context object, which can quickly eat up RAM on the device.