Call a public method in the Activity class from another class?

前端 未结 8 2180
无人及你
无人及你 2020-12-05 19:33

MAIN ACTIVITY

    public class MyActivity() extends Activity
    {
        onCreate()
        {
            MyClass myobj=new MyClass();    
        }
               


        
相关标签:
8条回答
  • 2020-12-05 20:18

    I had an inner class that I wanted to pull out into a more general library "Helper" class. I had the same issue you do. I got around it by making the helper class abstract, with a single abstract method. Then in my project package I extended the helper class with a constructor call in the specific class.

    public class MyActivity extends Activity {
        onCreate() {
            MyHelperClass = new MyHelperClass(this, "foobar");
        }
    
        public void myMethod() {
            // Code...
        }
    }
    
    // In a different file
    public class MyHelperClass extends HelperClass {
        private MyActivity mInstance;
    
        public MyHelperClass(MyActivity act, String data) {
            super();
            this.mInstance = act;
            this.mActivity = act;  // Useful for calling generic Activity methods in the HelperClass
            this.mData = data;
        }
    
        protected void callMyActivityMethod() {
            mInstance.myMethod();
        }
    }
    
    // In a different file
    public abstract class HelperClass {
        protected Activity  mActivity;
        protected String    mData;
    
        public HelperClass() {
            // Subclass will set variables
        }
    
        protected abstract void callMyActivityMethod();
    
        // More code for all the other stuff the class does
    }
    

    In this way, I have a helper class that contains the vast majority of the "work", and all I have to do is make a subclass with the constructor and one method in order to get access to the calling activity's method of interest.

    0 讨论(0)
  • 2020-12-05 20:20

    This is probably the best way to do it. This is how I'm doing it. It's called a Singleton Design Pattern:

    public class MyActivity extends Activity {
        private static MainActivity instance;
    
        public static MainActivity getInstance() {
         if(instance==null){
              setInstance(this);
            }
            return instance;
        }
    
        public static void setInstance(MainActivity instance) {
            MainActivity.instance = instance;
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setInstance(this);
        }
    }
    
    0 讨论(0)
提交回复
热议问题