0

I've been building controls for the vehicle I want to control. However I'm still quite new to Java and android developing. So I am looking for best practices to handle multiple buttons from the UI. So far I've managed to create 2 buttons which are on the same screen, see code below. Is this a correct way to handle and create buttons?

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

}

That code actually works - I'm planning to create threads inside the switch-case statements too, I haven't figured out that one yet. Any input would be appreciated.

4

1 回答 1

3

第 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
        }
    }
}
于 2013-10-30T20:41:26.237 回答