让我们说我的主屏幕有很多按钮。
我想创建一个其中所有Button侦听器都在其中的类,并在每次按下按钮时从我的main方法调用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?
答案 0 :(得分:1)
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);
}
});
}