简体   繁体   English

我们可以调用在 MainActivity 中的同一类中声明的方法,而不是在 onCreate 或 android studio 中的其他方法中吗?

[英]Can we call a method declared in same class in MainActivity not in onCreate or other methods in android studio?

I have created a method in MainActivity class.我在 MainActivity 类中创建了一个方法。 I know I can call that in onCreate method and other methods in that same class.我知道我可以在 onCreate 方法和同一个类中的其他方法中调用它。 But can I call that method outside onCreate and other methods but in MainActivity class?但是我可以在 onCreate 和其他方法之外但在 MainActivity 类中调用该方法吗?

When I try to do that, I get an error.当我尝试这样做时,出现错误。

The error I am getting is "Invalid method declaration" but I have already declared the method below.我得到的错误是“无效的方法声明”,但我已经声明了下面的方法。 I am just calling it here.我只是在这里调用它。

package com.example.android.kabaddicounter;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    //Can we call this method here? Its giving an error

    displayForPakistan(25);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void displayForPakistan(int score){
        TextView scoreView = (TextView) findViewById(R.id.score_pakistan);
        scoreView.setText(String.valueOf(score));

    }

    public void displayForIndia(int score){
        TextView scoreView = (TextView) findViewById(R.id.score_india);
        scoreView.setText(String.valueOf(score));

    }
}

The answer is no you can't, unlike other codeflows the android codeflow runs only through callback functions called from the devices internal system.答案是否定的,您不能,与其他代码流不同,android 代码流仅通过从设备内部系统调用的回调函数运行。

You can for example call a method from other method but if that method will not be call from any of the callbacks , both will never get excited例如,您可以从其他方法调用一个方法,但如果该方法不会从任何回调中调用,则两者都不会兴奋

With that been said, you have the exception of listener which can also call methods but there are just another type of callbacks话虽如此,您有侦听器的例外,它也可以调用方法,但只有另一种类型的回调

Read about activitys lifecycle to learn more阅读活动生命周期以了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM