一. MainActivity.java
package activity.Movies; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.nostra13.universalimageloader.core.ImageLoader; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import Adapter.MyPagerAdapter; import Bean.MovieBean; public class MainActivity extends AppCompatActivity { private TextView area; private TextView title; private EditText edit_name; private ViewPager viewPager; private LinearLayout linelayout; private ImageView image_cover; private List<ImageView> images; private MyPagerAdapter pagerAdapter; private List<MovieBean.ResultBean.ActSBean> list=new ArrayList<>(); private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if (msg.what == 0){ int currentItem = viewPager.getCurrentItem(); viewPager.setCurrentItem(currentItem+1); //持续发送空消息 handler.sendEmptyMessageDelayed(0,2888); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); title = (TextView) findViewById(R.id.title); area = (TextView) findViewById(R.id.area); edit_name = (EditText) findViewById(R.id.edit_name); viewPager = (ViewPager) findViewById(R.id.viewPager); linelayout = (LinearLayout) findViewById(R.id.linear_layout); image_cover = (ImageView) findViewById(R.id.image_cover); //轮播图延时发送空消息,展示在某一页面 viewPager.setCurrentItem(list.size()%100000); handler.sendEmptyMessageDelayed(0,2888); } //点击搜索影片的方法 public void find(View view){ //先清空集合,再执行异步任务 list.clear(); MyTask task = new MyTask(); String movies = edit_name.getText().toString(); String encode = URLEncoder.encode(movies); if (!TextUtils.isEmpty(encode)){ task.execute("http://op.juhe.cn/onebox/movie/video?key=2189382719d77ad949572c948ad39072&q="+edit_name.getText().toString()); }else{ Toast.makeText(MainActivity.this,"请输入完整的影片名称!",Toast.LENGTH_SHORT).show(); } } //异步任务加载数据 class MyTask extends AsyncTask<String,String,String> { @Override protected String doInBackground(String... strings) { try { //客户端 HttpClient client = new DefaultHttpClient(); //get请求方式 HttpGet httpGet = new HttpGet(strings[0]); //响应对象 HttpResponse response = client.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode==200){ InputStream inputStream = response.getEntity().getContent(); String json = streamToString(inputStream,"utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { MovieBean movieBean = new Gson().fromJson(result, MovieBean.class); //调用设置适配器的方法,设置展示数据 if (movieBean != null){ list.addAll(movieBean.getResult().getAct_s()); Log.i("集合", MainActivity.this.list.toString()); //初始化小圆点的方法 initCircle(); setAdapter(); } //把查询到的影片信息赋值 ImageLoader.getInstance().displayImage(movieBean.getResult().getCover(),image_cover); title.setText("片名:"+movieBean.getResult().getTitle()); area.setText("区域:"+movieBean.getResult().getArea()); } } private void initCircle() { //首先需要一个集合记录这些小圆点的图片,,,,当页面切换的时候,可以从集合中取出imageView进行显示图片的设置 images = new ArrayList<>(); //先清空移除所有的view linelayout.removeAllViews(); //集合数据对应的圆点 for (int i = 0;i<list.size();i++){ ImageView imageView = new ImageView(MainActivity.this); //刚开始显示时的顔色 if (i == 0){ imageView.setImageResource(R.drawable.button_selected); }else { imageView.setImageResource(R.drawable.button_select_no); } //把设置好的视图添加到集合中 images.add(imageView); //加入到线性布局中显示 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); //圆点之间的间距 params.setMargins(8,0,8,0); linelayout.addView(imageView,params); } } //设置适配器的方法 public void setAdapter() { //设置无限轮播图的适配器 if (pagerAdapter == null){ pagerAdapter = new MyPagerAdapter(MainActivity.this,list); viewPager.setAdapter(pagerAdapter); //viewPager页面改变的监听事件 viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { //如果选中了这一页,,,当前小圆点红色,,,否则绿色 for (int i = 0;i<images.size();i++){ if (i == position%images.size()){ images.get(i).setImageResource(R.drawable.button_selected); }else { images.get(i).setImageResource(R.drawable.button_select_no); } } } @Override public void onPageScrollStateChanged(int state) { } }); }else{ pagerAdapter.notifyDataSetChanged(); } } //Json数据解析的自定义方法 private String streamToString(InputStream inputStream, String encode) { try { //转换流 InputStreamReader streamReader = new InputStreamReader(inputStream, encode); //缓冲流 BufferedReader reader = new BufferedReader(streamReader); //缓冲区 StringBuilder builder = new StringBuilder(); //读取数据 String data = null; while ((data = reader.readLine())!=null){ builder.append(data); } //关流,返回数据 reader.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } }
二. 自定义适配器类
package Adapter; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.List; import Bean.MovieBean; public class MyPagerAdapter extends PagerAdapter{ //声明变量 private Context context; private List<MovieBean.ResultBean.ActSBean> list; public MyPagerAdapter(Context context, List<MovieBean.ResultBean.ActSBean> list) { this.context = context; this.list = list; } @Override public int getCount() { return Integer.MAX_VALUE; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.FIT_XY); ImageLoader.getInstance().displayImage(list.get(position%list.size()).getImage(),imageView); container.addView(imageView); return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } }
三. ImageLoader类的辅助工具类
package Util;
import android.app.Application;
import android.content.Context;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import java.io.File;
public class ImageUtil extends Application{
@Override
public void onCreate() {
super.onCreate();
inconfig(this);
}
//配置ImageLoader类
public void inconfig(Context context){
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.memoryCacheExtraOptions(480, 800) // default = device screen dimensions
.threadPriority(Thread.NORM_PRIORITY - 1) // default
.tasksProcessingOrder(QueueProcessingType.FIFO) // default
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
.memoryCacheSize(2 * 1024 * 1024)
.memoryCacheSizePercentage(13) // default
.diskCache(new UnlimitedDiscCache(cacheDir)) // default
.diskCacheSize(50 * 1024 * 1024)
.diskCacheFileCount(100)
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
.imageDownloader(new BaseImageDownloader(context)) // default
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config);
}
}
四. 自定义请求网络数据的Bean封装类
五. 布局xml文件:
1. activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="activity.Movies.MainActivity"> <LinearLayout android:id="@+id/line" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true"> <EditText android:singleLine="true" android:inputType="text" android:hint="请输入电影名称" android:id="@+id/edit_name" android:layout_width="288dp" android:layout_marginLeft="30dp" android:layout_height="wrap_content" /> <Button android:text="搜索" android:onClick="find" android:layout_width="80dp" android:layout_height="40dp" android:layout_marginLeft="45dp"/> </LinearLayout> <RelativeLayout android:id="@+id/relative" android:layout_height="288dp" android:layout_marginTop="3dp" android:layout_below="@+id/line" android:layout_width="match_parent"> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent"/> <LinearLayout android:layout_alignBottom="@+id/viewPager" android:layout_centerHorizontal="true" android:layout_marginBottom="18dp" android:orientation="horizontal" android:id="@+id/linear_layout" android:layout_width="100dp" android:layout_height="28dp" > </LinearLayout> </RelativeLayout> <ImageView android:layout_width="500dp" android:layout_height="318dp" android:id="@+id/image_cover" android:layout_marginTop="50dp" android:layout_below="@+id/relative" android:layout_centerHorizontal="true"/> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="30dp" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" > <TextView android:id="@+id/title" android:textSize="18sp" android:layout_marginLeft="106dp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/area" android:textSize="18sp" android:layout_marginLeft="36dp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </RelativeLayout>
2. drawable文件夹下轮播图中小圆点的实现代码
(1). button_selected.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#00FF7F"></solid>
<corners android:radius="6dp"></corners>
<size android:width="8dp" android:height="8dp"></size>
</shape>
(2). button_select_no.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFA07A"></solid>
<corners android:radius="6dp"></corners>
<size android:width="8dp" android:height="8dp"></size>
</shape>
最后在AndroidManifest.xml中声明网络请求权限和ImageLoader的name属性。