【问题标题】:custom ListView doesn't refresh自定义 ListView 不刷新
【发布时间】:2013-06-04 09:59:23
【问题描述】:

我对 Android 上的 ListView 有疑问。不是真正的 ListView,因为它是在 Sherlock Fragment 上实现的。所以特别是: 我有 2 个类,一个是Fragment,一个是普通的ActivityActivity 从网上下载一个文件,Fragment 中有一个下载文件的列表。
这是我的Fragment 适配器:

File mydownload = new File (Environment.getExternalStorageDirectory()+ "/Sample Folder");
int i = 0;
while ( i < mydownload.list().length) {
    adapter.add(mydownload.list()[i]);
    i++;
}
setListAdapter(adapter);

所以适配器会捕获 Sample Folder 中的所有文件并将其放在列表中。当我下载文件时,适配器不会刷新列表(我认为是因为它处于不同的上下文中,但我不知道解决方案)。要刷新,我必须关闭并打开应用程序。我尝试了很多可能的解决方案,但没有任何帮助。

编辑:我的Fragment 代码:

public class AppleFragment extends SherlockListFragment{    
/** An array of items to display in ArrayList */
private static ArrayAdapter<String> adapter = null; 


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    /** Creating array adapter to set data in listview */

    adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), R.layout.liststyle, new ArrayList<String>());
    View v = super.onCreateView(inflater, container, savedInstanceState);
    /** Setting the array adapter to the listview */
    File mydownload = new File (Environment.getExternalStorageDirectory()+ "/Gazzetta Ufficiale");
    int i = 0;
    while ( i < mydownload.list().length) {
        adapter.add(mydownload.list()[i]);
        i++;
    }
    setListAdapter(adapter);
    return v;

}    

@Override
public void onStart() {     
    super.onStart();
    getListView().setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapter, View view, int position, long id){
            String gazza = (String) adapter.getItemAtPosition(position);
            File pdf = new File (Environment.getExternalStorageDirectory()+ "/Gazzetta Ufficiale" + "/" + gazza);
            try {
                Uri path = Uri.fromFile(pdf);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



        }   
    });

    /** Setting the multiselect choice mode for the listview */
    //getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    getListView().setOnItemLongClickListener(new OnItemLongClickListener() { 

        public boolean onItemLongClick (AdapterView<?> arg0, View view, int position, long id){
            final int pos = position;
            String gazza = (String) arg0.getItemAtPosition(position);
            final File pdf = new File (Environment.getExternalStorageDirectory()+ "/Gazzetta Ufficiale" + "/" + gazza);
            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which){
                    case DialogInterface.BUTTON_POSITIVE:
                        //Yes button clicked
                        pdf.delete();
                        adapter.remove(adapter.getItem(pos));
                        adapter.notifyDataSetChanged();
                        break;

                    case DialogInterface.BUTTON_NEGATIVE:
                        //No button clicked
                        dialog.dismiss();
                        break;
                    }
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("Vuoi eliminare la Gazzetta?").setPositiveButton("Elimina", dialogClickListener)
                .setNegativeButton("Annulla", dialogClickListener).show();
            return true;
        }
    });
}   
}

下载活动:

private class DownloadFile extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... sUrl) {
        try {
            File mydownload = new File (Environment.getExternalStorageDirectory()+ "/Gazzetta Ufficiale");

            if (!mydownload.exists()){
                mydownload.mkdir();
            }

            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);     

            String url = sUrl[0];
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            }
               request.setAllowedNetworkTypes(
                        DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                        .setAllowedOverRoaming(false)
                        .setTitle("Gazzetta " + sUrl[1])
                        .setDescription(sUrl [2] + ". In download..")
                        .setDestinationInExternalPublicDir("/Gazzetta Ufficiale", sUrl[1] + ".pdf");

            manager.enqueue(request);


        } 
        catch (Exception e) {
        }
        return null;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        toast = Toast.makeText(Gazzetta_detail.this, "Download in corso...", Toast.LENGTH_SHORT);
        toast.show();
    }
}

【问题讨论】:

  • 你有没有尝试在获取新数据后调用适配器上的 notifyDataSetChanged() 方法?
  • 我在活动中获取新数据,如何为片段上的适配器调用此方法?抱歉,这是我的第一个申请!
  • 好的,我对片段不是很熟悉,但无论如何我都会尽力帮助你。我想你正在调用一个函数来从活动中更新你的列表视图,对吧?在这种情况下,您仍然可以在更新函数结束时调用我建议您的方法,在它内部,例如:adapter.notifyDataSetChanged()。
  • 我编辑问题,查看我的 2 个类的整个代码
  • 我有点困惑..您将 AsyncTask 称为活动,这实际上是错误的。我仍然相信您仅在使用 onCreateView() 启动应用程序时触发更新列表.为了使事情更容易,只需在布局中添加一个按钮,该按钮只需调用 adapter.notifyDataSetChanged() 并查看是否发生了某些事情,如果是这样,这意味着在您获取数据后您没有正确触发适配器上的更新或者您没有更新包含新数据的列表。

标签: android listview refresh android-fragmentactivity


【解决方案1】:

在您的适配器上调用notifyDataSetChanged()

可以在此查看有关如何/何时调用 notifyDataSetChanged() 的一些其他细节 Google I/O video.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多