2012-09-02 39 views
0

我有MainMenu。有3种不同的ImageButton用于开始新的活动。一切工作正常,但我想知道是可能的另一种方式来编码。我从一个按钮的示例代码中拿出了这个,我认为它看起来不太好:为每个按钮设置新的OnClickListener()从ImageButtons开始新的活动

public class MainMenu extends Activity implements OnClickListener{ 

ImageButton firstModule; 
ImageButton secondModule; 
ImageButton thirdModule; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main_menu); 

    //init buttons 
    firstModule = (ImageButton) findViewById(R.id.imageButton1); 
    secondModule = (ImageButton) findViewById(R.id.imageButton2); 
    thirdModule = (ImageButton) findViewById(R.id.imageButton3); 

    firstModule.setOnClickListener(this); 
    secondModule.setOnClickListener(this); 
    thirdModule.setOnClickListener(this); 
} 
public void onClick(View v) { 

    switch(v.getId()){ 
    case R.id.imageButton1: 
     startActivity(new Intent(MainMenu.this, BasicFunctions.class)); 
     break; 
    case R.id.imageButton2: 
     startActivity(new Intent(MainMenu.this, GpsModule.class)); 
     break; 
    case R.id.imageButton3: 
     startActivity(new Intent(MainMenu.this, Graphic3D.class)); 
     break; 
    } 

} 

}

回答

3

更优雅的方式是实施View.OnClickListenerActivity,然后点击过程里面你ActivityonClick()方法中。它为您提供了一个View对象作为参数,您可以使用view.getId()方法检索视图的ID,然后您可以使用switch块为布局中的每个Button执行操作。希望这可以帮助。

+0

我试过了你的解决方案(第一篇文章编辑过),但按钮没有反应点击。我现在没有想法。 –

+0

我在switch()中做了一个断点,看起来方法OnClic()从不使用。 –

+0

我忘了为每个按钮设置onClickListener,发布编辑。非常感谢Egor的帮助! –