I have a Refresh button that I would like to make visible depending on the situation.
When the Refresh button is clicked I can make it invisible without a problem, however, I cannot make it visible again once the AsyncTask
process finishes. I have trouble passing the MenuItem
value back to the AsyncTask
.
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.refresh_action_provider, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_refresh:
item.setVisible(false); //hide refresh button
setSupportProgressBarIndeterminateVisibility(true);
Toast.makeText(getApplicationContext(), "REFRESH CLiCKED", Toast.LENGTH_SHORT).show();
new DownloadNewsTask().execute();
return true;
}
return false;
}
You could pass your item in your task's constructor, store it and make it visible in onPostExecute
method:
public class DownloadNewsTask extends AsyncTask<...> {
private final MenuItem item;
public DownloadNewsTask(MenuItem item) {
this.item = item;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
item.setVisible(true);
}
...
}
And then:
new DownloadNewsTask(item).execute();
You can also have the item be a member of your activity class and access it from your task if it is defined as an inner class of your activity:
public class TestActivity extends Activity {
protected MenuItem refreshItem;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.refresh_action_provider, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
this.refreshItem = item;
item.setVisible(false); // hide refresh button
setSupportProgressBarIndeterminateVisibility(true);
Toast.makeText(getApplicationContext(), "REFRESH CLiCKED", Toast.LENGTH_SHORT).show();
new DownloadNewsTask().execute();
return true;
}
return false;
}
public class DownloadNewsTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// your stuff...
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
refreshItem.setVisible(true);
}
}
}