假设我的主屏幕有很多按钮。
我想创建一个类,其中所有按钮监听器都在其中,并在每次按下按钮时从我的主方法中调用 onClick。
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);}
}
}
}
有没有办法调用 onClick 方法,例如:
Buttons allButtons = new Buttons();
allButtons.onClick(btn1);
还是我的逻辑错误?
................................................
已经检查
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?
最佳答案
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);
}
});
}
关于java - Android:从其他类调用 main 中按钮的 OnClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22677169/