Calling methods from other classes in Android

后端 未结 3 1818
说谎
说谎 2020-12-22 05:44

I am trying to call a method from another class but I get an exception error.

I have two classes and class 1 is the main class

Class 1 has an onclick<

相关标签:
3条回答
  • 2020-12-22 06:25

    I know this is a little bit late, but having spent 2 full days to find a solution, this one definitely works for me, that could be useful to others:

    1. Define the required function within first class (MainActivity which extends Activity) as a Static:

      public static int getScreenH(){
          Integer H = Sheight;
          return H;
      }
      
    2. Then in the other class (class ResizeTextView extends TextView) call the function:

      Integer hh = MainActivity.getScreenH();
      

    That's it!! The problem was that the calling class was an extension of TextView so none of the methods available within Activity could be used!

    0 讨论(0)
  • 2020-12-22 06:40

    If I've understood your question correctly, if you want to call the methods in a extended class, you need to make sure those methods are either public or protected.

    Also omit the classname, eg just call method() not class.method()

    Just to elaborate on this some more, here is some code I just cooked up:

    class class1 {
        private void privateMethod() {
            // do nothing
        }
        protected void protectedMethod() {
            // do nothing
        }
        public void publicMethod() {
            // do nothing
        }
    }
    class class2 extends class1 {
        private void testMethod() {
            privateMethod();    // error - not visible
            protectedMethod();    // works
            publicMethod(); // also works
        }
    }
    
    0 讨论(0)
  • 2020-12-22 06:41

    EDITED (because Kevin deleted previous answer):

    Android is a bit specific in this situation..

    In case one of your class is Activity and the other is "helper" class, situation implies than you need to create an instance of the "helper" class in Activity class. Something like

    private Helper helper = new Helper(this);
    

    and than you can call methods of helper class, anywhere in your Activity by using:

    helper.nameOfMethod(requiredParameters);
    

    It might happen that your ClassA is Activity (so it extends Android Activity class) and ClassB is Activity too but extends ActivityA. In this situation you should be able to use methods of ActivityA from ActivityB just by calling it by method name (without explicitly writing where is your method stored).

    methodFromActivityB(parameters);
    

    Hope it's a bit easier to understand it now.

    0 讨论(0)
提交回复
热议问题