呼叫其他班的Andr​​oid方法方法、Andr、oid

2023-09-05 05:16:23 作者:放爱一条生路

我试图调用从另一个类中的方法,但我得到一个异常错误。

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

我有两个阶级和阶级1是主类

I have two classes and class 1 is the main class

1类有一个的onclick 方法,它从另一个类调用方法的onclick

Class 1 has an onclick method which calls the method from another class onclick.

我有文本框和edittexts在声明的类1。

I have textfields and edittexts declared in class 1.

2类具有这些功能,并使用if语句。

Class 2 has functionality for these and uses if statements.

我从第2类扩展类1所以2级使用的变量。

I extend class 1 from class 2 so class 2 uses the variables.

哪些方面,我还可以从其他类中的方法在机器人。

What are the ways I can call methods from other classes in android.

目前,我只是用中调用类2类1的方法:

At the moment I just call the method from class 2 in class 1 by using:

class1.method(); 

但这似乎并不奏效。鸭preciate任何意见表示感谢。

but this doesn't seem to be working. Appreciate any advice thanks.

编辑:

我现在已经在1级创建一个变量:

I have now created in class 1 a variable:

static class2 object;

这是在这个我称之为的onclick

object.class2method();

我得到一个NullPointerException异常错误的感谢。

I get a nullPointerexception error thanks.

推荐答案

如果我正确地理解你的问题,如果你要调用一个扩展类的方法,你需要确保这些方法是公共或受保护

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.

还省略了类名,比如就叫办法()不是 class.method()

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

只是为了阐述这个更多一些,这里是一些code我刚熟了:

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
    }
}