本文主要是介绍在fragment中用ViewFlipper做网络图片轮播手动+自动+点击事件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本人刚步入大三,从大二开始自学Android,已经学了一年了,所以我还是个小菜,希望老鸟们勿喷。本博客分享个人开发经验,用于互相交流学习。
由于项目中需要用到图片轮播所以花了一天的时间把它弄了出来,我也是第一次来做,数据缓存还没有做,如有更好的方法请与我分享。(1021766585@qq.com)
先需求分析一下
UI主线程中初始化ViewFlipper
我是在fragment来做的底部导航,所以我的ViewFlipper在fragment中。
public class FragmentHome extends Fragment {private ViewFlipper flipper;private GridView gridView;private List<Map<String, Object>> dataList;private SimpleAdapter sim_adapter;private String url="http://******/microclass/index.php?g=service&m=index&a=index";private Handler handler = new Handler();@Override@Nullablepublic View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {// TODO Auto-generated method stubView view = inflater.inflate(R.layout.fragment_home,container,false);flipper = (ViewFlipper) view.findViewById(R.id.viewFlipper);new ThreadGetHomeImages(url, handler, flipper, getActivity()).start();return view;}
将接口的URL传递给网络线程获取所有的JSON数据(由于一些安全性问题,不方便将JSON数据完全分享出来)
{"flag":"Success","msg":"\u9996\u9875\u6eda\u52a8\u56fe\u7247","data":[{"slide_name":"\u4e60\u5927\u5927\u7684\u8868\u60c5\u8bf4\u660e\u4e86\u4e00\u5207\uff01","slide_pic":"http:\/\/**********\/microclass\/data\/upload\/20160916\/57dbdacb2e1ff.jpg","slide_url":"http:\/\/**********\/microclass\/index.php?g=&m=article&a=index&id=27"},{"slide_name":"\u5fae\u8bfb\u4e66\uff01","slide_pic":"http:\/\/******\/microclass\/data\/upload\/20160916\/57dbb7cdbc81b.jpg","slide_url":"http:\/\/*******\/microclass\/index.php?g=portal&m=article&a=index&id=26"},{"slide_name":"\u61a7\u61ac\u7684\u7ae5\u5e74","slide_pic":"http:\/\/**********\/microclass\/data\/upload\/20160916\/57dbd6de2036c.jpg","slide_url":"http:\/\/********\/microclass\/index.php?g=portal&m=article&a=index&id=28"}]}
public class ThreadGetHomeImages extends Thread {private String url,str,imageUrl;private ViewFlipper flipper;private List<ImageView> imageViews = new ArrayList<ImageView>();private List<CarouselImage> data;//方便数据的写入和读取private ImageView temp;private Handler handler;private Context context;private TranslateAnimation rightInAnim,leftOutAnim,rightOutAnim,leftInAnim;private float startX;private HttpClient client;public ThreadGetHomeImages(String url,Handler handler,ViewFlipper flipper,Context context) {// TODO Auto-generated constructor stubthis.url = url;this.handler = handler;this.flipper = flipper;this.context = context;}@Overridepublic void run() {// TODO Auto-generated method stubtry {client = new DefaultHttpClient();HttpGet request = new HttpGet(); //用GET方法request.setURI(new URI(url));//设置URLHttpResponse response = client.execute(request);//发送请求返回响应HttpEntity entity = response.getEntity();//获得网页内容实体if(entity != null){str = EntityUtils.toString(entity);//如果不为空就转换成字符串类型Log.i("Json", str);data = parseJson(str);//对获取到的JSON字符串进行解析赋值给List<CarouselImage> datafor(int i = 0; i<data.size();i++){//通过循环将图片的URL数据读取出来imageUrl = data.get(i).getImageUrl();Log.i("ImageUrl", imageUrl+"");temp = new ImageView(context);temp.setImageBitmap(getBitmap(imageUrl));//getbitmap方法获取网络图片temp.setScaleType(ScaleType.CENTER_CROP);//控制图片的显示imageViews.add(temp);//添加到ImageView集合中}}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (URISyntaxException e) {// TODO Auto-generated catch blocke.printStackTrace();}handler.post(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubsetVeiwFlipperAnim();//在主线程中更新UI}});super.run();}private List<CarouselImage> parseJson(String json) {List<CarouselImage> items = new ArrayList<CarouselImage>();//new一个CarouselImage集合try {JSONObject object = new JSONObject(json);String state = object.getString("flag");if(state.equals("Success")){JSONArray ImagesData = object.getJSONArray("data");for(int i = 0;i<ImagesData.length();i++){CarouselImage image = new CarouselImage(); JSONObject item = ImagesData.getJSONObject(i);image.setImageName(item.getString("slide_name"));image.setImageUrl(item.getString("slide_pic"));image.setTextUrl(item.getString("slide_url"));Log.i("ImageUrl", item.getString("slide_pic"));items.add(image);}return items;}else{Log.i("STATE", "数据获取失败!!");}} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}public static Bitmap getBitmap(String imageUri) {Log.v("ImageUrl", "getbitmap:" + imageUri);// 显示网络上的图片Bitmap bitmap = null;try {URL myFileUrl = new URL(imageUri);HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();conn.setDoInput(true);conn.connect();InputStream is = conn.getInputStream();bitmap = BitmapFactory.decodeStream(is);is.close();Log.v("download finished", "image download finished." + imageUri);} catch (OutOfMemoryError e) {e.printStackTrace();bitmap = null;} catch (IOException e) {e.printStackTrace();Log.v("getbitmap", "getbitmap bmp fail---");bitmap = null;}return bitmap;}private void setVeiwFlipperAnim() {for(int i =0;i<imageViews.size();i++){flipper.addView(imageViews.get(i));//将之前做好的ImageView集合中的元素逐一添加添加到ViewFlipper中}//设置ViewFlipper的滑动行为的动画// 图片从右侧滑入rightInAnim = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 1.0f,Animation.RELATIVE_TO_PARENT, 0.0f,Animation.RELATIVE_TO_PARENT, 0.0f,Animation.RELATIVE_TO_PARENT, 0.0f);rightInAnim.setDuration(1000);// 图片从左侧滑出leftOutAnim = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f,Animation.RELATIVE_TO_PARENT, -1.0f,Animation.RELATIVE_TO_PARENT, 0.0f,Animation.RELATIVE_TO_PARENT, 0.0f);leftOutAnim.setDuration(1000);// 图片从右侧滑出rightOutAnim = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f,Animation.RELATIVE_TO_PARENT, 1.0f,Animation.RELATIVE_TO_PARENT, 0.0f,Animation.RELATIVE_TO_PARENT, 0.0f);rightOutAnim.setDuration(1000);// 图片从左侧滑入leftInAnim = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -1.0f,Animation.RELATIVE_TO_PARENT, 0.0f,Animation.RELATIVE_TO_PARENT, 0.0f,Animation.RELATIVE_TO_PARENT, 0.0f);leftInAnim.setDuration(1000);// 正常情况左侧划出,右侧滑入flipper.setOutAnimation(leftOutAnim);flipper.setInAnimation(rightInAnim);flipper.setFlipInterval(5000);//设置自动切换时间flipper.startFlipping();flipper.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubint action = event.getAction();switch (action) {case MotionEvent.ACTION_DOWN:startX = (int) event.getX();//flipper.stopFlipping();// 当手指按下时,停止图片的循环播放。并记录当前x坐标Log.i("count", flipper.getDisplayedChild()+"");break;case MotionEvent.ACTION_MOVE:break;case MotionEvent.ACTION_UP:if (event.getX() - startX > 100) { // 手指向右滑动,左侧滑入,右侧滑出flipper.setInAnimation(leftInAnim);flipper.setOutAnimation(rightOutAnim);flipper.showPrevious();flipper.startFlipping();} else if (startX - event.getX() > 100) {// 手指向左滑动,右侧滑入,左侧滑出flipper.setInAnimation(rightInAnim);flipper.setOutAnimation(leftOutAnim);flipper.showNext();flipper.startFlipping();}else if(startX - event.getX()<10||event.getX()-startX<10){//当左右滑动的坐标差<10时,可以确定为点击动作,解决了OnTouch和OnClick的冲突//Toast.makeText(context, "当前索引"+flipper.getDisplayedChild(), Toast.LENGTH_SHORT).show();data.get(flipper.getDisplayedChild());Intent intent = new Intent();intent.putExtra("titleName",data.get(flipper.getDisplayedChild()).getImageName());//传递文章标题intent.putExtra("textUrl", data.get(flipper.getDisplayedChild()).getTextUrl());//传递文章的URLintent.setClass(context, WebActivity.class);context.startActivity(intent);}break;}//返回false只执行一次监听,返回true会一直进行监听return true;}}); }
}
CarouselImage类
public class CarouselImage {private String imageName; private String imageUrl;private String textUrl;public String getImageName() {return imageName;}public void setImageName(String imageName) {this.imageName = imageName;}public String getImageUrl() {return imageUrl;}public void setImageUrl(String imageUrl) {this.imageUrl = imageUrl;}public String getTextUrl() {return textUrl;}public void setTextUrl(String textUrl) {this.textUrl = textUrl;}
}
fragment加载的xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginBottom="50dp"android:orientation="vertical"android:weightSum="3" ><ViewFlipper android:id="@+id/viewFlipper"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"></ViewFlipper><GridView android:id="@+id/gridView"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="2"android:layout_marginTop="20dp"android:gravity="center_horizontal"android:numColumns="3"android:stretchMode="columnWidth"></GridView>
</LinearLayout>
贴下图
这篇关于在fragment中用ViewFlipper做网络图片轮播手动+自动+点击事件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!