2

我有一个刷新按钮,我想根据情况使其可见。

单击“刷新”按钮时,我可以毫无问题地使其不可见,但是,一旦该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;
}
4

1 回答 1

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);
    }
}
}
于 2012-11-13T10:28:30.310 回答