如何在片段中设置gridview适配器

时间:2013-09-03 11:29:58

标签: android

您好我在Fragment中的AsyncTask从JSON字符串获取图像网址。现在我想把它们放到gridview中。我可以在Activity上执行此操作,但不能在Fragment中执行此操作。有人可以帮我解决吗?

我在这里发布了类似的问题:implement AsyncTask in Fragment android。并找到了在片段中使用asynctask的答案,但不是GridView。

我的代码:

public class SalesFragment extends Fragment {
    GridView gridView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View gv = inflater.inflate(R.layout.hot_sales, null);
        gridView = (GridView) gv.findViewById(R.id.grid_view);
        bindGridview();
        return gv;
    }

    public void bindGridview() {

       new MyAsyncTask(getActivity(),gridView).execute("");
    }

    class MyAsyncTask extends AsyncTask<String, String, String> {
        GridView mGridView;
        Activity mContext;
        Response response;
       public  MyAsyncTask(Activity context,GridView gview) {
         this.mGridView=gview;
         this.mContext=context;
        }

       protected String doInBackground(String... params)  {


            if(file.exists()) {
                try{
                       //Parsing data
                    } catch (FileNotFoundException e) {
                       e.printStackTrace();
                    } catch (@SuppressWarnings("hiding") IOException e){
                       e.printStackTrace();
                    }
            }else{
                System.out.println("Error");
            }
            return null;
            }

       @Override
       protected void onPostExecute(String result) {

            super.onPostExecute(result);

            //List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

            for(Sales sales : this.response.sales){
                HashMap<String, String> hm = new HashMap<String,String>();

                if (sales.Categories1){
                    //Fetching the data
                        }
                    }
                }
            }
       }
    }
}

1 个答案:

答案 0 :(得分:0)

找到答案。以下代码解决了它。

SimpleAdapter adapter = new SimpleAdapter(getActivity(), aList1,
R.layout.grid_sales, new String[] { "shop_image"},new int[] { R.id.sale_image });