簡體   English   中英

Android Java-處理主要活動中多個按鈕的正確方法

[英]Android java - correct way to handle multiple buttons from main activity

我一直在為要控制的車輛構建控件。 但是我對Java和android開發還是很陌生。 因此,我正在尋找最佳實踐來處理UI中的多個按鈕。 到目前為止,我已經設法在同一屏幕上創建2個按鈕,請參見下面的代碼。 這是處理和創建按鈕的正確方法嗎?

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    /* Left Button */
    Button btnLeft = (Button)findViewById(R.id.btnLeft);
    btnLeft.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:   
                    // Create thread
                case MotionEvent.ACTION_UP:
                    // End Thread
                }
        return false;
        }
    });

    /* Right button */
    Button btnRight = (Button)findViewById(R.id.btnRight);
    btnRight.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:   
                    // Create thread
                case MotionEvent.ACTION_UP:
                    // End Thread
                }
        return false;
        }
    });
}

}

該代碼實際上有效-我也計划在switch-case語句內創建線程,但我還沒有想到。 任何輸入將不勝感激。

步驟1:使活動實現OnClickListener

第2步:覆蓋方法onClick

public class MainActivity extends Activity implements OnClickListener {

    Button btnLeft, btnRight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /* Left Button */
        btnLeft = (Button) findViewById(R.id.btnLeft);
        btnLeft.setOnTouchListener(this);

        /* Right button */
        btnRight = (Button) findViewById(R.id.btnRight);
        btnRight.setOnTouchListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == btnleft) {
            // do stuff for button left
        }
        if (v == btnRight) {
            // do stuff for button right
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM