我使用选择器通过将每个按钮的背景设置为drawable/selectors.xml
来更改某些按钮的颜色。
当用户按下按钮时,按钮的颜色会发生变化。但是,如果我想查看用户按下哪个按钮怎么办?如何设置事件以检查USER对按钮的单击。
答案 0 :(得分:1)
使用isPressed()方法可以做类似的事情
Button myBu= (Button) findViewById(R.id.button);
myBu.isPressed();// example how to use it
Log.d("is pressed?", "" + myBu.isPressed());//false, not pressed
myBu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("is pressed", "" + v.isPressed());//true,pressed
}
});
答案 1 :(得分:1)
如果您的布局有多个Button
,则需要尝试实施View.OnClickListener以查找Button
点击的内容。
public class MainActivity extends AppCompactActivity implements View.OnClickListener
{
private Button button1,button2,button3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public void onClick(View view)
{
switch (view.getId())
{
//handle multiple view click events
case R.id.button1:
Log.e("Which Button click","Button1 is clicked");
break;
case R.id.button2:
Log.e("Which Button click","Button2 is clicked");
break;
case R.id.button3:
Log.e("Which Button click","Button3 is clicked");
break;
}
}
}
我希望它对你有所帮助。
答案 2 :(得分:0)
您可以像这样使用View.OnTouchListener:
mTouchListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent ev) {
int action = ev.getAction();
switch(v.getId()) {
case R.id.button1:
if(action==MotionEvent.ACTION_DOWN) {
mButtonOnePressed = true;
}
else if(action==MotionEvent.ACTION_UP||action==MotionEvent.ACTION_CANCEL) {
mButtonOnePressed = false;
break;
..and so on
}
return false;
}
};
并为每个按钮:
mButton1.setOnTouchListener(mTouchListener);