Question

I've created a onClickListener in the onCreate() state. Once the program is running I'm in onResume() state, how come when I call the onClickListener in the onResume() state it works?

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

}
Was it helpful?

Solution

When you are in onCreate() , you are registering your buttons's onClick event into the anonymous class View.OnClickListener().

Now this class has a method (onClick()) that is waiting for the button click event to occur.

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.

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 i.e. "onClick()".

So it does not matter if you are in onCreate or onResume once you register your button with onClickListener.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top