我想从一个没有将View夸大的类中生成Toast。
我的程序中有3个班级。这些是:
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);
...
}
}
和
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();
}
}
StartVoiceRecognition类中的Toast导致Screen类中的布局损坏。我如何在StartVoiceRecognition中放入Toast,以免发生这种情况?
答案 0 :(得分:1)
how to call toast from another class in android
将此方法放在另一个类中。通常,我们将这种通用方法放在名为Utils的程序包中,然后,您可以在任何需要的地方使用它。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
StartVoiceRecognition.makeToast(this, "This is a Toast msg.");
}
}
和
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();
}
}