Answer the question
In order to leave comments, you need to log in
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();
Answer the question
In order to leave comments, you need to log in
Pass to MyClass a pointer to the activity/context in which toasts should be shown.
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.
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 questionAsk a Question
731 491 924 answers to any question