我有这个代码,当我触摸并释放按钮时执行操作。 但事实证明,即使我还没有发布它,它会立即释放
switch (v.getId())
{
case(R.id.turnoffall):
if(event.getAction() == MotionEvent.ACTION_DOWN);
{
v.setBackgroundResource(R.drawable.boffall2);
Toast.makeText(getApplicationContext(), "Pressed! ! !",Toast.LENGTH_SHORT).show();
}
if(event.getAction() == MotionEvent.ACTION_UP);
{
v.setBackgroundResource(R.drawable.boffall1);
Toast.makeText(getApplicationContext(), "Released.",Toast.LENGTH_SHORT).show();
}
break;
}
我该怎么办呢?
答案 0 :(得分:1)
尝试像这样更改代码。我测试了它。它有效!
main_activity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_gravity="center" />
</FrameLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button button = (Button) findViewById(R.id.button);
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (view.getId()) {
case R.id.button:
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
Toast.makeText(getApplicationContext(), "Pressed! ! !", Toast.LENGTH_SHORT).show();
return true;
case MotionEvent.ACTION_UP:
Toast.makeText(getApplicationContext(), "Released! ! !", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
default:
return false;
}
}
});
}
}