Java 点击后按钮(图像)不改变
我有一个非常基本的应用程序,它有一个按钮,可以在点击时播放声音。它会一直播放,直到按下/轻触按钮,一旦您取消轻触或不触碰按钮,声音就会停止。你点击(按住)声音继续播放,一旦按钮未被触动,声音停止。现在我有了一个按钮图像,当它被触摸时(音乐播放),它应该会改变,当它未被触摸时(音乐停止),它会回到默认状态。当我使用onClickListener时,这个东西工作得很好,但一旦我将它更改为onTouchListener,点击时按钮图像就不会改变。以下是MainActivity.java代码:Java 点击后按钮(图像)不改变,java,android,button,Java,Android,Button,我有一个非常基本的应用程序,它有一个按钮,可以在点击时播放声音。它会一直播放,直到按下/轻触按钮,一旦您取消轻触或不触碰按钮,声音就会停止。你点击(按住)声音继续播放,一旦按钮未被触动,声音停止。现在我有了一个按钮图像,当它被触摸时(音乐播放),它应该会改变,当它未被触摸时(音乐停止),它会回到默认状态。当我使用onClickListener时,这个东西工作得很好,但一旦我将它更改为onTouchListener,点击时按钮图像就不会改变。以下是MainActivity.java代码: pack
package com.example.firozkaoo2222.myapplication;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import static com.example.firozkaoo2222.myapplication.R.raw.police;
public class MainActivity extends AppCompatActivity {
private MediaPlayer policeSound;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button policeSounds = findViewById(R.id.police);
policeSounds.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (policeSound == null) {
policeSound = MediaPlayer.create(getApplicationContext(), R.raw.police);
}
int eventPadTouch = event.getAction();
switch (eventPadTouch) {
case MotionEvent.ACTION_DOWN:
// start playing sound , in your case:
policeSound.start();
return true;
case MotionEvent.ACTION_UP:
// stop playing sound , in your case:
policeSound.pause();
return true;
}
return false;
}
});}}
activity_main.xml的代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/police"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/custom_button" />
</RelativeLayout>
cutom_button.xml的代码:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@drawable/button_pressed" />
<item
android:drawable="@drawable/button_default" />
</selector>
Touch listener会使用click listener,它将永远不会到达选择器。因为您使用的是
pressed state
,所以您可以使用policsounds来模拟按下的状态。setPressed(boolean)
所以请更改它
switch (eventPadTouch) {
case MotionEvent.ACTION_DOWN:
// start playing sound , in your case:
policeSound.start();
policeSounds.setPressed(true)
return true;
case MotionEvent.ACTION_UP:
// stop playing sound , in your case:
policeSound.pause();
policeSounds.setPressed(false)
return true;
}
注意:为了让您信服,您可以将policysounds
声明在oncreate
之外,而不是将其作为局部变量final