//先添加数据
private void init() {
GridView gv_me= (GridView) findViewById(R.id.gv_me);
GridView gv_more= (GridView) findViewById(R.id.gv_more);
melist=new ArrayList<>();
morelist=new ArrayList<>();
meadapter = new MyAdapter(this,melist);
gv_me.setAdapter(meadapter);
moreadapter = new MyAdapter(this,morelist);
gv_more.setAdapter(moreadapter);
//设置条目点击事件
gv_me.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
morelist.add(melist.get(i));//添加到更多集合
melist.remove(i);//自己的集合中删除
//重新给适配器添置
meadapter.setData(melist);
moreadapter.setData(morelist);
}
});
//给更多的条目添加点击事件
gv_more.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
melist.add(morelist.get(i));
morelist.remove(i);
moreadapter.setData(morelist);
meadapter.setData(melist);
}
});
}
通过异步,得到网络数据,并给各个集合赋值
class My extends AsyncTask<String,Integer,String>{
@Override
protected String doInBackground(String... strings) {
try {
StringBuffer sb=new StringBuffer();
URL urll=new URL(strings[0]);
HttpURLConnection conn= (HttpURLConnection) urll.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if(200==conn.getResponseCode()){
InputStream in=conn.getInputStream();
String line=null;
BufferedReader br=new BufferedReader(new InputStreamReader(in));
while((line=br.readLine()) != null){
sb.append(line);
}
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
System.out.println(s);
Gson gson=new Gson();
Bean b=gson.fromJson(s,Bean.class);
System.out.println("===b"+b);
ArrayList<Bean.Channel> li=b.channel;
for (int i = 0; i <li.size() ; i++) {
melist.add(li.get(i).channel_me);
morelist.add(li.get(i).channel_more);
}
//给适配器赋值
meadapter.setData(melist);
moreadapter.setData(morelist);
}
}
注意,异步的实例化和执行操作,必须在主线程操作