public class MainActivity extends AppCompatActivity { String uri="https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=6&page=1"; int i = 0; List<ImageBean.NewslistBean> list = new ArrayList<ImageBean.NewslistBean>(); Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); adapter.notifyDataSetChanged(); int what = msg.what; switch(what){ case 0: adapter.notifyDataSetChanged(); break; case 1: adapter.notifyDataSetChanged(); int aaa = (int) msg.obj; if(list.size()!=0) { vp.setCurrentItem(aaa % list.size()); } break; } } }; private MyAdapter adapter; private ImageLoader instance; private ViewPager vp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); vp = (ViewPager) findViewById(R.id.vp); instance = ImageLoader.getInstance(); adapter = new MyAdapter(); vp.setAdapter(adapter); respart(); lunbu(); } private void lunbu() { new Thread(){ @Override public void run() { super.run(); while(true){ Message msg=new Message(); msg.what=1; i++; msg.obj=i; handler.sendMessage(msg); SystemClock.sleep(1000); } } }.start(); } private void respart() { new Thread(){ @Override public void run() { super.run(); try { URL url = new URL(uri); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line=null; StringBuffer sb=new StringBuffer(); while((line=bufferedReader.readLine())!=null){ sb.append(line); } Gson gson=new Gson(); ImageBean imageBean = gson.fromJson(sb.toString(), ImageBean.class); List<ImageBean.NewslistBean> newslist = imageBean.getNewslist(); list.addAll(newslist); Message msg=new Message(); msg.what=0; handler.sendMessage(msg); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } class MyAdapter extends PagerAdapter{ @Override public int getCount() { return 5000; } @Override public boolean isViewFromObject(View view, Object object) { return view==object; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public Object instantiateItem(ViewGroup container, int position) { View view = View.inflate(MainActivity.this, R.layout.activity_list, null); ImageView imageView = view.findViewById(R.id.iv_li); TextView textView = view.findViewById(R.id.tv_li); if(list.size()!=0) { textView.setText(list.get(position % list.size()).getTitle()); instance.displayImage(list.get(position % list.size()).getPicUrl(), imageView); } container.addView(view); return view; } } }
ViewPager 无限轮滑
最新推荐文章于 2020-06-01 19:44:08 发布