public class Buttons extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button btn1 = (Button) findViewById(R.id.button1);
Button btn2 = (Button) findViewById(R.id.button3); // did you mean R.id.button2?
// Create the onClickListener for btn1
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent ScrollViewTest = new Intent(this, ScrollViewTest.class);
startActivity(ScrollViewTest);
}
});
// Create the onClickListener for btn2
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent ScrollViewTest = new Intent(this, CameraTest.class);
startActivity(CameraTest);
}
});
}
Android: Call OnClick for Buttons in main from an other class
-
22-06-2023 - |
Domanda
Lets say my main screen has a lot of Buttons.
I want to make a class in which all the Button listeners are inside and call the onClick from my main method each time I press a button.
public class Buttons extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onClick(View v) {
Button btn1 = (Button) findViewById(R.id.button1);
Button btn2 = (Button) findViewById(R.id.button3);
int viewId = v.getId() ;
if(viewId == R.id.button1){
Intent ScrollViewTest = new Intent(this, ScrollViewTest.class);
startActivity(ScrollViewTest);}
if(viewId == R.id.button2){
Intent ScrollViewTest = new Intent(this, CameraTest.class);
startActivity(CameraTest);}
}
}
}
Is there a way to call the onClick method like:
Buttons allButtons = new Buttons();
allButtons.onClick(btn1);
or is my logic wrong ?
........................................
Already checked
calling a method from an onClick listener
How to call onClick(View v) method explicitly in an Android? Is it possible?
Is there a method to set methods for multiple objects in one go?
Soluzione
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow