简体   繁体   English

android:在onResume()中运行的onCreate()中创建方法

[英]android: creating method in onCreate() running in onResume()

I've created a onClickListener in the onCreate() state. 我已经在onCreate()状态下创建了一个onClickListener。 Once the program is running I'm in onResume() state, how come when I call the onClickListener in the onResume() state it works? 程序运行后,我处于onResume()状态,当我以onResume()状态调用onClickListener时,它又如何工作呢?

Shouldn't there be a distinction between the states: 状态之间不应该有区别:

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        Button myButton= (Button) findViewById(R.id.button1);
        myButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                TextView tv= (TextView) findViewById(R.id.textView1);
                tv.setText("CIAO 1");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

When you are in onCreate() , you are registering your buttons's onClick event into the anonymous class View.OnClickListener() . 当您处于onCreate() ,您正在将按钮的onClick事件注册到匿名类View.OnClickListener()

Now this class has a method ( onClick() ) that is waiting for the button click event to occur. 现在,此类具有一个方法( onClick() ),该方法正在等待按钮单击事件发生。

Now imagine as you have asked a person to do a task when particular event will occur. 现在想象一下,当您要求某人在特定事件发生时执行任务。

In this case you have asked a " View.OnClickListener() " person to do a task " onClick() " when button click occurs. 在这种情况下,您已经要求“ View.OnClickListener() ”人员在按钮单击发生时执行任务“ onClick() ”。

Now even if you are in onResume(), and user presses that button, the "person" will be notified about the event and will perform the task ie "onClick()". 现在,即使您位于onResume()中,并且用户按下该按钮,“人员”也将收到有关事件的通知,并将执行任务“ onClick()”。

So it does not matter if you are in onCreate or onResume once you register your button with onClickListener. 因此,一旦在onClickListener中注册了按钮,就处于onCreate还是onResume中都没有关系。

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

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