简体   繁体   中英

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. I know I can call that in onCreate method and other methods in that same class. But can I call that method outside onCreate and other methods but in MainActivity class?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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