在asynctask之后麻烦使menuitem可见

时间:2012-11-13 10:24:27

标签: android android-asynctask actionbarsherlock menuitem

我有一个刷新按钮,我希望根据具体情况显示该按钮。

单击刷新按钮后,我可以将其隐藏而不会出现问题,但是,AsyncTask进程完成后,我无法再将其显示出来。我无法将MenuItem值传回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;
}

1 个答案:

答案 0 :(得分:6)

您可以在任务的构造函数中传递项目,将其存储并在onPostExecute方法中显示:

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);
    }

    ...
}

然后:

new DownloadNewsTask(item).execute(); 

如果项目被定义为您的活动的内部类,您还可以让该项目成为您的活动类的成员并从您的任务访问它:

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);
    }
}
}