Showing Toast in Android
We moved. Please visit this link for this post.
Toast is very good solution when need to notify user about something.
For example I always show Toast to the user when it wants to open SDCard which is not mounted (best practice).
I am going to show simple Toast which shows on the center of activity. Please check all methods, you will find a lot of interesting.
Toast msg = Toast.makeText(Main.this, "Message", Toast.LENGTH_LONG); msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2); msg.show();
Interesting method is makeText. 3-rd parameter represents how long should be showed Toast.
Example:
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
* Class which shows how to show toast
*
* @author FaYna Soft Labs
*/
public class Main extends Activity {
private Button clickBtn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
clickBtn = (Button) findViewById(R.id.click);
clickBtn.setText("Show message");
clickBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast msg = Toast.makeText(Main.this, "Message", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
});
}
}
Showing notification such this one is very good practice. I am sure that it is useful approach.
Categories: Android, Android how to