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

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

MAIN ACTIVITY

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


        
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 20:09

    You have to pass instance of MainActivity into another class, then you can call everything public (in MainActivity) from everywhere.

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
    
        // Instance of AnotherClass for future use
        private AnotherClass anotherClass;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // Create new instance of AnotherClass and
            // pass instance of MainActivity by "this"
            anotherClass = new AnotherClass(this);
        }
    
        // Method you want to call from another class
        public void myMethod(){
            ...
        }
    }
    

    AnotherClass.java

    public class AnotherClass {
    
        // Main class instance
        private MainActivity mainActivity;  
    
        // Constructor
        public AnotherClass(MainActivity activity) {
    
            // Save instance of main class for future use
            mainActivity = activity;  
    
            // Call method in MainActivity
            mainActivity.myMethod();
        }
    }
    

提交回复
热议问题