How to reference the current or main activity from another class

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

    I'm new to android so my suggestion may look guffy but what if you'll just create a reference to your activity as a private property and assign that in OnCreate method? You can even create your CustomActivity with OnCreate like that and derive all your activities from your CustomActivity, not generic Activity provided by adnroid.

    class blah extends Activity{
      private Activity activityReference;
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            activityReference = this;
        }
    
    }
    after that you could use that the way you want, i.e. in

    Intent i = new Intent(activityReference, SomeOtherActivity.class)
    

    etc

提交回复
热议问题