Reputation: 2112
I'd like to generate a Toast from a class that does not have a View inflated from it.
I have 3 classes in my program. These are:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent screenIntent = new Intent(this, Screen.class);
this.startActivity(screenIntent);
StartVoiceRecognition StartVoiceRecognitionChild = new StartVoiceRecognition();
StartVoiceRecognitionChild.makeToast();
}
}
,
public class Screen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen);
//species field
tvSpecies = this.findViewById(R.id.textboxSpeciesxml);
tvSpecies.setText(MainActivity.szSpecies);
...
}
}
and
public class StartVoiceRecognition extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void makeToast(Context context) {
Toast.makeText(getApplicationContext(), "toast content here", Toast.LENGTH_SHORT).show();
}
}
The Toast in StartVoiceRecognition class causes the layout in Screen class to be corrupted. How do I put a Toast in StartVoiceRecognition so this does not happen?
Upvotes: 0
Views: 109
Reputation: 150
how to call toast from another class in android
Put this method in another class. Usually we put this common methods in a package called Utils, then, you can use it wherever you want.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
StartVoiceRecognition.makeToast(this, "This is a Toast msg.");
}
}
and
public class StartVoiceRecognition extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public static void makeToast(Context mContext,String message){
Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
}
}
Upvotes: 1