Question:
I'm trying to make a Toast
appear as soon as the user chooses a Listview
option, however, when the user chooses the option, Acticity
is loaded first and then Toast
appears, and what I really want is the opposite.
Here's the code:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
LayoutInflater layoutInflater = getLayoutInflater();
int layout = R.layout.toast_custom;
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.toast_layout_root);
view = layoutInflater.inflate(layout, viewGroup);
TextView tv_texto = (TextView) view.findViewById(R.id.texto);
TextView slogan_text = (TextView) view.findViewById(R.id.slogan);
tv_texto.setText("Aguarde...");
slogan_text.setText("Carregando " + opcoes[position]);
Toast toast = new Toast(context);
if (opcoes[position] == 1){
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(view);
toast.show();
Intent intent = new Intent(context, Eventos.class);
startActivity(intent);
}
}
How can I make the Toast
run first and then start the Activity
?
Answer:
I believe an asyncTask solves:
if (opcoes[position] == 1){
new AsyncTask().execute();
}
…
private class AsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
try {
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(view);
toast.show();
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
Intent intent = new Intent(context, Eventos.class);
startActivity(intent);
}
}
I hope it helps.