I'm going to be using a toast in my application for testing purposes. I am only new to the Android environment and I'm not very familiar with toasts. I know a standard toast it like this: Toast.makeText(context, text, duration).show();
. However, instead of applying a String of text into the 'text' section, I want to apply a variable.
Here is what I have written:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_next);
Button send = (Button) findViewById(R.id.bSend);//Import button1 (Send)
send.setOnClickListener(new OnClickListener() {//Set an onClickListener for the button to work
public void onClick(View v) {
Toast.makeText(getApplicationContext(), cText, Toast.LENGTH_LONG).show();
}//end method
});//End Send
}//End onCreate
cText
is a variable used in a different method present in the class. Any suggestions on how I can get the toast to contain the contents of cText
? Thanks in advance.
May be you an Try this
public class MainActivity extends Activity {
String Text="MainActivity Message"; //Global variable
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_next);
Button send = (Button) findViewById(R.id.bSend);//Import button1 (Send)
send.setOnClickListener(new OnClickListener() {//Set an onClickListener for the button to work
public void onClick(View v) {
//Declaring two variables.
//You can also declare it as global.
//but global variable must be initialized before creating toast otherwise you will get NPE and lead to you application crash
String cText="Toast Message";
int val=1;
Toast.makeText(getApplicationContext(), cText, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "vlaue is "+val, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public String getMessage(){
return "Text from Function";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With