Click button from method that is outside the oncreate in Android
The following is a basic striped down overview of one of my projects. I would like for a method outside of the oncreate to be able to click a button that is declaired in the oncreate but i cannot figure out how.
Here is my code: I would like to be able to performClick()
the webButton
from the method clickButton()
but it does not work. If that is not possible i would atleast like to know how to start the intent that is trying to be started when the button is clicked from instide the clickButton()
method.
Thank you in advance!!
public class cphome extends Activity {
static final int check =111;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button webButton = (Button) findViewById(R.id.button1);
webButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), web.class);
startActivity(myIntent);
}
}开发者_StackOverflow中文版);
}
public void clickbutton(){
webButton.performClick();
}
}
This is a really strange pattern. I would suggest you to do something like that instead:
public class cphome extends Activity {
static final int check =111;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button webButton = (Button) findViewById(R.id.button1);
webButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
performClickAction();
}
});
}
public void performClickAction(){
Intent myIntent = new Intent(this, web.class);
startActivity(myIntent);
}
}
精彩评论