context vs views

前端 未结 2 584
星月不相逢
星月不相逢 2020-12-17 21:38

can anyone explain the difference between context and views and when do we go for context or view ? In most of the program I find either context or

2条回答
  •  暖寄归人
    2020-12-17 22:11

    We need to understand how View is constructed and what is Context.

    View has three constructors, all of which use Context as an argument.

    In Activity, if view is inflated programmatically as against in XML, view is inflated a View is by using LayoutInflater.

    LayoutInflater takes Context as an argument and internally saves it in a class level field.

    LayoutInfater layoutinflater = LayoutInflater.from(this);
    

    where "this" is the Activity instance.

    When inflater inflates view i.e. :

    inflater.inflate(R.id.some_view, parent, null),

    it is internally passing the saved context field to the constructor of View.

    View always takes a Context as an argument and this is obvious because views live in some Context which is the Activity.

    To answer your question, when context is needed to be passed to a method which itself is in Activity, you can write "this". If method is not in Activity, and you need to pass Context, then remember that View which has taken Context as a parameter, saves the object reference in a class level field. We can get this object reference by writing view.getContext().

提交回复
热议问题