在BroadcastReceiver中更新gridview

时间:2014-08-09 12:27:32

标签: android gridview broadcastreceiver fragment

我有一个带有gridview的片段,其中包含可下载项目列表,我需要更新gridview下载的项目,但是我在BroadcastReceiver中获取gridview有些困难。 bellow是我的BroadcastReceiver代码:

BroadcastReceiver griddownloadReceiver = new BroadcastReceiver() {

      @Override
      public void onReceive(Context context, Intent intent) {
       //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       //check if the broadcast message is for our Enqueued download
       long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

       GridView gv1=(GridView)getView().findViewById(R.id.grid_view);
       adapter = (GridAdapter) gv1.getAdapter();
       //final GridAdapter adapter = (GridAdapter) ((GridView) getView()).getAdapter();
       adapter.setDownloadFinished(referenceId);

       // Ask the adapter to refresh the ListView
       adapter.notifyDataSetChanged();

      }
};//end of broadcast reciever

我应该用什么来代替这两行f代码?

 GridView gv1=(GridView)getView().findViewById(R.id.grid_view);
 adapter = (GridAdapter) gv1.getAdapter();

1 个答案:

答案 0 :(得分:0)

  

我应该用什么来代替这两行f代码?

在片段onCreateView()中保存对私有字段中适配器的引用,然后在griddownloadReceiver中访问该片段,该片段应放在该片段中。

不要忘记在onResume注册并在onPause取消注册。

然后确保方法setDownloadFinished(referenceId)正常工作。