How to reference the current or main activity from another class

后端 未结 13 803
难免孤独
难免孤独 2021-01-30 12:39

I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager, I need to access some Activity. But ofte

相关标签:
13条回答
  • 2021-01-30 13:06

    I think this is the solution to this, you get your context static and then reference it statically.

    0 讨论(0)
  • 2021-01-30 13:07

    You can implement the necessary methods in your activity and implement a Handler. Then, simply pass a handler instance to your classes, where you can obtain a message for handler and send it to target.

    0 讨论(0)
  • 2021-01-30 13:13

    Handle the Intent in the class you want to do these methods, and send your information to it in a Bundle like so:

        Intent i = new Intent("android.intent.action.MAIN");
        i.setComponent(new ComponentName("com.my.pkg","com.my.pkg.myActivity"));
        Bundle data = new Bundle();
    
        i.putExtras(data);
    
        startActivityForResult(i);
    

    Then use an OnActivityResultListener to grab the new data.

    0 讨论(0)
  • 2021-01-30 13:14

    I found a way to get the Activity to a non-activity class that I have not seen discussed in forums. This was after numerous failed attempts at using getApplicationContext() and of passing the context in as a parameter to constructors, none of which gave Activity. I saw that my adapters were casting the incoming context to Activity so I made the same cast to my non-activity class constructors:

    public class HandleDropdown extends Application{
    ...
        public Activity activity;
    ...
    public HandleDropdown() {
        super();
    }
    public HandleDropdown(Activity context) {
        this.activity = context;
        this.context = context;
    }
    public void DropList(View v,Activity context) {
        this.activity = context;
        this.context = context; 
    ...
    }
    

    After doing this cast conversion of Context to Activity I could use this.activity wherever I needed an Activity context.

    0 讨论(0)
  • 2021-01-30 13:15

    If you already have a valid context, just use this: Activity activity = (Activity) context;

    0 讨论(0)
  • 2021-01-30 13:19

    There are many ways for Activities communication.

    you can use:

    • the startActivityForResult method

    • a system of broadcast message and receiver (you can broadcast an event from the actual activity, and register a receiver in the target activity. Remember that the target activity must be previously initialized and non finished)

    • as you say, store a reference of the target activity wherever you need.
    0 讨论(0)
提交回复
热议问题