如何在android中单击后隐藏按钮

e0bqpujr  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(382)

程序运行良好。问题是,您必须单击两次才能将其隐藏。
如果我只想点击一下,播放按钮就消失了呢?我的代码哪里错了。
布局:

<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);
    }
rqenqsqc

rqenqsqc1#

您需要将处理隐藏的代码移出新的 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);
}

相关问题