How to get my activity context?

前端 未结 7 1710
小鲜肉
小鲜肉 2020-12-02 08:49

I don\'t really get the idea behind how this whole thing works really, so if I have some class A that need the context of a class B which extends <

相关标签:
7条回答
  • 2020-12-02 09:02

    In Kotlin will be :

    activity?.applicationContext?.let {
             it//<- you context
            }
    
    0 讨论(0)
  • 2020-12-02 09:06

    you pass the context to class B in it's constructor, and make sure you pass getApplicationContext() instead of a activityContext()

    0 讨论(0)
  • 2020-12-02 09:09

    The best and easy way to get the activity context is putting .this after the name of the Activity. For example: If your Activity's name is SecondActivity, its context will be SecondActivity.this

    0 讨论(0)
  • 2020-12-02 09:09

    If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested. I do not see much the problem of having the many instances of A having their own pointers to B, not sure if that would even be that much of an overhead.

    But if that is the problem, a possibility is to keep the pointer to A as a sort of global, avariable of the Application class, as @hasanghaforian suggested. In fact, depending on what do you need the context for, you could even use the context of the Application instead.

    I'd suggest reading this article about context to better figure it out what context you need.

    0 讨论(0)
  • 2020-12-02 09:11

    You can create a constructor using parameter Context of class A then you can use this context.

    Context c;

    A(Context context){ this.c=context }

    From B activity you create a object of class A using this constructor and passing getApplicationContext().

    0 讨论(0)
  • 2020-12-02 09:12

    Ok, I will give a small example on how to do what you ask

    public class ClassB extends Activity
    {
    
     ClassA A1 = new ClassA(this); // for activity context
    
     ClassA A2 = new ClassA(getApplicationContext());  // for application context. 
    
    }
    
    0 讨论(0)
提交回复
热议问题