8

As soon as the layout is created I want a button to be clicked automatically and I use button.performClick() for that.

The problem is that it doesn't work. It looks like I can't do that during the onCreate, onStart, onResume method. At what point is the button and its events created, so I can perform a click on it?

This

@Override
protected void onResume() {
    super.onResume();
    mybutton.performClick();
}

doesn't work.

ali
  • 10,569
  • 20
  • 77
  • 128
  • 1
    Look at my answer http://stackoverflow.com/questions/14706886/how-can-get-x-and-y-position-of-an-image-in-android/14707052#14707052 – user370305 Mar 05 '13 at 13:30
  • 2
    are you sure that doing `setContentView()`, `findViewById()`, `setOnClickListener()` and `performClick()` does not work? I'm just curious! – vault Mar 05 '13 at 13:33
  • They work. The button is just not clicked, but I don't get any error – ali Mar 05 '13 at 13:36

4 Answers4

32

This worked for me in a similar case:

mybutton.post(new Runnable(){
            @Override
            public void run() {
                 mybutton.performClick();
            }
});

This way the runnable will run only if the button is already loaded on the layout.

abbath
  • 2,345
  • 4
  • 27
  • 39
3

You need to use a ViewTreeObserver:

    ViewTreeObserver vto = mybutton.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            vto.removeOnGlobalLayoutListener(this);
            mybutton.performClick();
        }
    });
Raghav Sood
  • 79,170
  • 20
  • 177
  • 186
  • That would be a good choice in my situation if I would test this on devices with API>16 – ali Mar 05 '13 at 13:45
3

What I smell, seem you forget to add onClicklistner to your view, I tested your way its works fine, I did something like below:

define Button globally Button btn;

within onCreate()

btn=(Button)findViewById(R.id.button);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    dialog();
                }
            });

and within onResume()

@Override
    protected void onResume() {

        btn.performClick();
        super.onResume();
    }

It successfully showing a dialog!

RobinHood
  • 10,464
  • 4
  • 44
  • 92
0
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout);

    myButton = (Button) findViewById(R.id.myButton);
    myButton.setOnClickListener(this);
}


@Override
public void onStart() {
    myButton.performClick();
}

@Override
public void onClick(View v) {
    // DO STUFF
}
Niko
  • 7,663
  • 5
  • 43
  • 78