Transferring activity or context to another instance

Could you tell me what is best to transfer activityor contextto another instance (;)

But...

  • Which is better to go through? activityorcontext
  • Good idea to have activityas global (public static Activity activity)

here is my code. What would you change? (based on good android techniques)

+4
source share
5 answers

Activity , Activity, , . Activity extends Context, , , Context.

Context View, . , Context , Activity - Activity.getApplicationContext().

, , Activity , Activity, Activity Android (GC) , " ".

EDIT:

, Activity.findViewById(), . -, View (http://developer.android.com/reference/android/view/View.html#findViewById(int)), .

-, View Activity, WeakReference

+5

Helper Activity 'this' ,

MyHelperclass helper=new MyHelperclass(this);

Helper

Context context;
MyHelperClass(Context context){
this.context=context;
}

makeText() Toast.

+1

Context - , . , getApplicationContext(), getContext(), getBaseContext() this ( ). Context / , e.t.c.

Context Toast.makeText. Context . Context

Activity, , Intent.

0

Create a new interface and implement an Activity or Service or Intentservice in your class and return the context as a callback

public interface ContextWraperSolution {
    Context getContext();
}

Pass this interface as a constructor parameter to the non-Activity class and use it as

insanaceContextWraper.getContext()
0
source

To use context from another instance, you can create a static variable and then access it if you want to use

public class MyClassA(){
     public static Context context;

     private void setcontext()
     {
         context = MyClassA.this;
     }

}

public class MyClassB(){
     private Context classA_context = MyClassA.context;    
}
0
source

Source: https://habr.com/ru/post/1611871/


All Articles