用banner实现网络接口的轮播图

//自定义一个banner
public class MyBanner extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
Picasso.with(context).load((String) path).into(imageView);
}
}

//在Java中实现

public class MainActivity extends AppCompatActivity {

private Banner banner;
private User user;
private String dataUrl = "https://www.zhaoapi.cn/quarter/getAd";

Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case 0:
                String data = (String) msg.obj;
                Gson gson = new Gson();
                user = gson.fromJson(data, User.class);
                ArrayList pic = new ArrayList<>();
                for (int i = 0; i < user.getData().size(); i++) {
                    pic.add(user.getData().get(i).getIcon());
                }
                banner.setImageLoader(new MyBanner());
                banner.setImages(pic);
                banner.start();
                Toast.makeText(MainActivity.this, user.toString(), Toast.LENGTH_SHORT).show();
                break;

        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //找控件
    banner = (Banner) findViewById(R.id.banner);

    getBannerData();
}

private void getBannerData() {
    new Thread() {
        @Override
        public void run() {
            super.run();
            try {
                URL url = new URL(dataUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(3000);
                int code = connection.getResponseCode();
                if (code == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = connection.getInputStream();
                    String s = CharStreams.toString(new InputStreamReader(inputStream, "UTF-8"));
                    Message message = Message.obtain();
                    message.what = 0;
                    message.obj = s;
                    handler.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
}

}

你可能感兴趣的:(用banner实现网络接口的轮播图)