Working sample code for button.performClick()

2019-09-23 18:16发布

问题:

Can someone please put a working code example of button.performClick() assigned to a OnClickListener. The following code which I have used returns false for button.performClick()-

myButton.performClick()
 myButton.setOnClickListener ( new View.OnClickListener()
      {
           @Override
           public void onClick ( View view )
           {
              .............
           }
});

回答1:

button.performClick()

should be myButton.performClick(); then you should exec it after you register the OnClickListener for your myButton

myButton.setOnClickListener ( new View.OnClickListener()
      {
           @Override
           public void onClick ( View view )
           {
              .............
           }
});


myButton.performClick();


回答2:

Declare the button Button bmi;

exampleButton=(Button)findViewById(R.id.button1);

exampleButton.setOnClickListener(new OnClickListener()
         {public void onClick
         (View  v) { 
             Intent i = new Intent(getApplicationContext(), exampleActivity.class);
             startActivity(i);}
         });

Let me know if it helped you ;)



回答3:

 final Button button= (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO handle click
            }
        });

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