V
V
Vanes Ri_Lax2015-08-07 10:22:41
Java
Vanes Ri_Lax, 2015-08-07 10:22:41

How to call Toast from another class?

Hello, tell me please. I have a MainActivity and during the operation of which a new instance of the class is created
new MyClass();
In that class, something is done and the user needs to display a message

Toast.makeText(this,"Мое сообщение",Toast.LENGTH_LONG).show();

Me interests, what context in this case to me to specify? After all, this will not work here.
Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

6 answer(s)
G
GavriKos, 2015-08-07
@GavriKos

Pass to MyClass a pointer to the activity/context in which toasts should be shown.

D
Dante Faustoff, 2015-08-13
@StFaustoff

As an add-on to all the previous answers, you can try MyClass.this.
Only I will not understand such a tricky system to instantiate an Activity in another Activity.
757-tachka-na-prokachku-ostalos-tolko-pr

I
Ilya, 2015-08-07
@iissakin

As far as I remember, it is possible to pass getActivity().

Q
qqmthfck, 2015-08-12
@qqmthfck

getApplicationContext()

D
Dmitry Bolshakov, 2015-08-25
@enq3

Now it is necessary to show only toast, and then you need to change the state of the controls in the activity or return the result of the class, and you won’t get by with just passing the context.

public class MyClass {
    MyClassCallback callback;

    public MyClass() {
        if(callback != null)
            callback.done();
    }

    public void setCallback(MyClassCallback callback) {
        this.callback = callback;
    }

    public void perform() {
        if(callback != null)
            callback.done();
    }

    interface MyClassCallback {
        void done();
    }
}

public class MainActivity extends AppCompatActivity {
    private MyClass myClass;
    private MyClass.MyClassCallback myClassCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myClass = new MyClass();
        myClassCallback = new MyClass.MyClassCallback() {
            @Override
            public void done() {
                Toast.makeText(MainActivity.this, "Мое сообщение", Toast.LENGTH_LONG).show();
            }
        };
        myClass.setCallback(myClassCallback);
        myClass.perform();
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question