1

I'm trying to make my toast message disappear prematurely when the background is touched. The toast should disappear when every part of the screen is touched... I know the method is .cancel but I can't utilize it properly.. this is what I tried:

I tried with the .setontouchlistener method but it doesn't work... I'm new in android development so it would be appreciated to have a sample code to learn from... I'll show you my code, this is it:

public class MainActivity extends AppCompatActivity {
private LayoutInflater layoutInflater;
private RelativeLayout relalayout
private LinearLayout linelayout;
private ScrollView scrollayout;
public Toast toast;
private ImageView backgroundimg;

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activitymain);
    Bundle extradata1 = getIntent().getExtras();
    String textString = extradata1.getString("ImportedData");
    TextView mytext = (TextView) findViewById(R.id.text);
    relalayout = (RelativeLayout) findViewById(R.id.relalayout);
    linelayout = (LinearLayout) findViewById(R.id.linelayout);
    scrollayout = (ScrollView) findViewById(R.id.scrolllayout);
    backgroundimg = (ImageView) findViewById(R.id.imageView2);
    toast = new Toast(this);

 if (textString.equals("firstimported")) {

        String mytxt = "";
        StringBuffer sbuffer = new StringBuffer();
        InputStream is = this.getResources().openRawResource(R.raw.firsttext);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));


        try {

            while ((mytxt = reader.readLine()) != null) {
                sbuffer.append(mytxt + "\n");

            }

            mytext.setText(sbuffer);
            is.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
        String text = sbuffer.toString();
        SpannableString ss = new SpannableString(text);

ClickableSpan clickspan1 = new ClickableSpan() {
@Override
public void onClick(View widget) {
    Toast toast = Toast.makeText(MainActivity.this, "this is the toast",
    Toast.LENGTH_SHORT);
    toast.show();}
    @Override
    public void updateDrawState(TextPaint ds) {

        super.updateDrawState(ds);
        ds.setColor(Color.WHITE);
        ds.setUnderlineText(false);}
    };

    scrollayout.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        toast.cancel();
        return false;
    }
});
ss.setSpan(clickspan1, 52, 53, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

mytext.setText(ss);
        mytext.setMovementMethod(LinkMovementMethod.getInstance());

}
}

public void onBackPressed() {
    Intent intent = new Intent(MainActivity.this, OtherActivity.class);
    startActivity(intent);
    finish();
}

the activity crashes when I touch the screen.. so it just won't work.

3 Answers3

2

You have to declare the Toast object on your activity's variable

private Toast toast;

And then initialize it on your onClick method:

toast = Toast.makeText(MainActivity.this, "this is the toast",Toast.LENGTH_SHORT);
toast.show();

Also, on your onTouch you should check if the toast object is nul:

if(toast != null){
   toast.cancel();
}
Tiago Ornelas
  • 1,109
  • 8
  • 21
1

Try this

Toast toast; 
@Override
public void onClick(View widget) {
    toast = Toast.makeText(MainActivity.this, "this is the toast", Toast.LENGTH_SHORT);
    toast.show();
}
scrollayout.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(toast != null)
            toast.cancel();
        return super.onTouch(v, event);
    }
});

Update Answer as per the code

public class MainActivity extends AppCompatActivity {
    private ScrollView scrollayout;
    public Toast toast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activitymain);
        TextView mytext = (TextView) findViewById(R.id.text);
        scrollayout = (ScrollView) findViewById(R.id.scrolllayout);
        StringBuffer sbuffer = new StringBuffer();
        sbuffer.append("1234567890\n");
        sbuffer.append("1234567890\n");
        sbuffer.append("1234567890\n");
        sbuffer.append("1234567890\n");
        sbuffer.append("1234567890\n");
        sbuffer.append("1234567890\n");
        sbuffer.append("1234567890\n");
        sbuffer.append("1234567890\n");
        sbuffer.append("1234567890\n");
        sbuffer.append("1234567890\n");
        String text = sbuffer.toString();
        SpannableString ss = new SpannableString(text);
        ClickableSpan clickspan1 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                toast = Toast.makeText(MainActivity.this, "this is the toast", Toast.LENGTH_SHORT);
                toast.show();
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.WHITE);
                ds.setUnderlineText(false);
            }
        };
        scrollayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (toast != null) {
                    toast.cancel();
                    toast = null;
                }
                return false;
            }
        });
        ss.setSpan(clickspan1, 52, 53, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mytext.setText(ss);
        mytext.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

I have changed some values that you used as I didn't have all the resources, But major change you need to do is in the ClickSpan initialization and scrolllayout touch event. Please compare them. I got the following output with scrolling after the toast has been shown. enter image description here

Applogies for the long size gif.

Brijesh Joshi
  • 1,817
  • 1
  • 9
  • 24
  • it doesn't work if I do this the scrollbar stops moving. – user8467834 Feb 07 '19 at 10:50
  • Do you have any other layout over your scrollLayout? – Brijesh Joshi Feb 07 '19 at 11:23
  • @user8467834 Can you try with `return true;` inside your `onTouch` method or `return super.onTouch(v, event);` – Brijesh Joshi Feb 07 '19 at 11:26
  • the xml file is composed by: RelativeLayout, background image, Scrolllayout with inside it a RelativeLayout and a Textview. – user8467834 Feb 07 '19 at 11:32
  • have you tried with the change of the return value of the onTouch method. Caz i think that with `return super.onTouch(v, event);` your scrollLayout won't stop scrolling. – Brijesh Joshi Feb 07 '19 at 11:33
  • it gives me errors, but return MainActivity.super.onTouchEvent(event). prevents it from stopping. The problem is it doesn't actually make the toast disappear after the bar is touched.. :( – user8467834 Feb 07 '19 at 11:46
  • It won't be `return MainActivity.super.onTouchEvent(event)`, it will be `return super.onTouch(v, event);`. Check in the edited answer – Brijesh Joshi Feb 07 '19 at 12:04
  • cannot resolve method onTouch(android.view.View, android.view.MotionEvent)' – user8467834 Feb 07 '19 at 13:51
  • can you please edit all your code? So I can check it. Whatever that class file is. – Brijesh Joshi Feb 08 '19 at 04:26
  • I edited it I put most of the code hope it's more understandable now – user8467834 Feb 08 '19 at 08:30
  • @user8467834 Please check the updated answer. I found mistakes in your code and have corrected it. I have kept the code only which is necessary for the demo purpose. Please use only suitable code. The major part you need to check is in the ClickSpan and OnTouchListener. Just follow the answer and you'll get your solution. Also I have attached a gif of the output which is showing toast being cancelled as soon as i start scrolling. – Brijesh Joshi Feb 08 '19 at 09:53
  • You're great! That's right, it's working now, thanks a lot!!! I set your answer as corrected and upvoted :) – user8467834 Feb 08 '19 at 16:06
  • Do you think there is a way to further implement a CountDownTimer to this code without the App crashing to show the toast for longer time??......... like in Regis_AG answer of this question... https://stackoverflow.com/questions/2220560/can-an-android-toast-be-longer-than-toast-length-long – user8467834 Feb 08 '19 at 16:27
0

Toast.makeText returns a Toast object. Call cancel() on this object to cancel it.

Kartika Vij
  • 203
  • 3
  • 17