在网上搜了很多toast连续点击不显示,傻愣愣的我还被这个东西搞了一个下午
解决方案:
声明一个toast,例
private Toast mtoast;
然后把下面这个加入到你认为合适的地方
if(mtoast != null){
mtoast.cancel();
}
你就当做.canel()是清除mtoast为null ,但是不知道为什么我实验后发现mtoast.canel()并不等于null ,请求大哥们更正!!!!
首先我们要让吐司窗口(反正我就这么叫他)显示出来吧,那么这个判断必定得放在show()之前,网上很多文章都把.canel()放在show()之后,我也傻愣愣的照着他们的敲,还傻愣愣的发现不了这么简单的错误。
我出问题修改后的文件
java文件
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class BtnActivity extends AppCompatActivity {
private Button btn = null;
private ImageView img = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_btn);
//响应按钮点击事件1.找到控件
btn = (Button) findViewById(R.id.button1);
img = (ImageView) findViewById(R.id.imageView7);
//2.响应
btn.setOnClickListener(new View.OnClickListener() {
private Toast mtoast;
@Override
public void onClick(View v) {
//设置响应内容 吐司弹窗
//去掉其他留这个就是最基本的toast 现在是为显示实时toast的修改Toast.makeText(BtnActivity.this,"显示图片成功",Toast.LENGTH_SHORT).show();
if (mtoast != null){ //清除mtoast的内容 注意清除后motoast并不等于null 并且用这种方法吐司窗口可以实时最新的且连续点击不会不显示
mtoast.cancel();
}
if(img.getVisibility() == View.INVISIBLE){
img.setVisibility(View.VISIBLE);
mtoast=Toast.makeText(BtnActivity.this,"显示图片成功",Toast.LENGTH_SHORT);
}else if(img.getVisibility() == View.VISIBLE){
img.setVisibility(View.INVISIBLE);
mtoast=Toast.makeText(BtnActivity.this,"隐藏图片成功",Toast.LENGTH_SHORT);
}
mtoast.show();
}
});
}
}
布局文件XML 若要复制得修改图片
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
android:visibility="visible"
tools:context=".BtnActivity">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Button"
android:textSize="36sp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/imageView7"
android:layout_width="263dp"
android:layout_height="262dp"
android:layout_marginTop="32dp"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button1"
app:srcCompat="@drawable/head" />
</androidx.constraintlayout.widget.ConstraintLayout>