#java #android
#java #Android
Вопрос:
Программа работает хорошо. Проблема в том, что вам нужно нажать 2 раза, прежде чем вы сможете ее скрыть.
Что, если я хочу всего один щелчок, и кнопка воспроизведения исчезнет? Где мой код неправильный.
Макет:
<Button
android:id="@ id/button111"
android:layout_width="75dp"
android:layout_height="80dp"
android:foregroundGravity="center_vertical|center|center_horizontal"
android:onClick="playSong"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="@drawable/play" />
Java:
public void playSong(View v) {
this.songIntent = new Intent(Main4Activity.this, BackgroundSoundService.class);
this.songIntent.putExtra("song", "suara_" randomResult);
final Button myButton = (Button) findViewById(R.id.button111);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myButton.setVisibility(View.GONE);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(SHARED_KEY_BUTTON_HIDE, true);
editor.apply();
}
});
startService(this.songIntent);
}
Комментарии:
1. если вы используете clicklistener, то почему
android:onClick="playSong"
?2. я хочу воспроизвести и скрыть кнопку, если пользователь нажмет кнопку
3. Поскольку вы установили
android:onClick="playSong
в XML, кнопка выполнит этот метод, как только вы нажмете на нее. ВнутриplaySong()
вы переопределяете ееOnClickListener
, поэтому, если вы нажмете на нее во второй раз, будет выполнен этот прослушиватель, который скрывает кнопку. Копирование-вставка этого кода из прослушивателя вplaySong
метод должно сделать это.
Ответ №1:
Вам нужно переместить код, который обрабатывает скрытие, из нового onClickListener
и поместить его прямо в playSong
метод.
public void playSong(View v) {
this.songIntent = new Intent(Main4Activity.this, BackgroundSoundService.class);
this.songIntent.putExtra("song", "suara_" randomResult);
final Button myButton = (Button) findViewById(R.id.button111);
myButton.setVisibility(View.GONE);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(SHARED_KEY_BUTTON_HIDE, true);
editor.apply();
startService(this.songIntent);
}