0

メインメニューがあります。新しいアクティビティを開始するための 3 つの異なる ImageButtons があります。すべてが正常に機能しますが、これをコーディングする別の方法が考えられます。ボタンが 1 つのサンプル コードからこれを取得しましたが、見栄えがよくないと思います。ボタンごとにnew OnClickListener()を設定します。

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;
    }

}

}

4

1 に答える 1

3

より洗練された方法は、あなたのView.OnClickListener内部に実装してから、あなたのメソッドActivity内でクリックを処理することです。引数としてオブジェクトを提供し、メソッドを使用してビューの ID を取得できます。次に、ブロックを使用して、レイアウト内のすべてのアクションを実装できます。お役に立てれば。onClick()ActivityViewview.getId()switchButton

于 2012-09-02T22:33:34.913 に答える