动态添加图像到android中的gridview

时间:2016-05-30 18:22:43

标签: android gridview

我正在尝试将我的SD卡中的图像添加到gridview中。我正在使用这种方法阅读图像:

     public void getImages()
        {
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES), "AppsCameraSpy");
            if(mediaStorageDir.exists())
            {
                String[] strings = mediaStorageDir.list();
                imageTitles = new ArrayList<String>(Arrays.asList(strings));
                Log.d(TAG, "the files are: " + imageTitles);

            }
            try
            {
                for(File file : mediaStorageDir.listFiles())
                {
                    files.add(file);
                    images.add(BitmapDrawable.createFromPath(file.getAbsolutePath()));
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                Log.d(TAG,"Got some exceptoin ");
            }
        }

现在,我将以上值传递给gridview:

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_gallery, container, false);

        gridView = (GridView)view.findViewById(R.id.gridView);
        Log.d(TAG,"I am gallery");
        getImages();

        gridView.setAdapter(new GridViewAdapter(getActivity(),images,imageTitles,files));

        return view;
    }

一切正常。但是,问题是如果将新图像添加到文件夹AppsCameraSpy,我的网格视图不会显示它们。

因为我在onCreateView中设置适配器,根据生命周期只调用一次。

现在,我应该如何修改我的代码以动态地将图像添加到gridview。

请帮我回答这个问题。

1 个答案:

答案 0 :(得分:1)

我在您现有的代码中添加了一些新代码。我希望以下代码适合您

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_gallery, container, false);

    gridView = (GridView)view.findViewById(R.id.gridView);
    Log.d(TAG,"I am gallery");
    getImages();

    GridViewAdapter adapter = new GridViewAdapter(getActivity(),images,imageTitles,files);
    gridView.setAdapter(adapter);

    Handler handler = new Handler();

    final Runnable r = new Runnable() {
        public void run() {
            getImages();
            adapter.adapter.notifyDataSetChanged();
            handler.postDelayed(this, 1000);
        }
    };
    handler.postDelayed(r, 1000);


    return view;
}