how to call a method in another Activity from Activity

后端 未结 6 1836
广开言路
广开言路 2020-11-27 21:34

\'m developing an Android Application in which I have

I\'ve two classes class A and Class B .

In class A , I tried the code Snippets like below,

6条回答
  •  庸人自扰
    2020-11-27 21:59

    If you need to call the same method from both Activities why not then use a third object?

    public class FirstActivity extends Activity 
    {  
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main2);
    
        }      
    
        // Utility.method() used somewhere in FirstActivity
    }
    
    public class Utility {
    
        public static void method()
        {
    
        }  
    
    }
    
    public class SecondActivity extends Activity 
    {  
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main2);
    
            Utility.method();
    
        }
    }
    

    Of course making it static depends on the use case.

提交回复
热议问题