How to reference the current or main activity from another class

后端 未结 13 826
难免孤独
难免孤独 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: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.

提交回复
热议问题