我一直在为要控制的车辆构建控件。但是我对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
}
}
}