本人刚步入大三,从大二开始自学Android,已经学了一年了,所以我还是个小菜,希望老鸟们勿喷。本博客分享个人开发经验,用于互相交流学习。
由于项目中需要用到图片轮播所以花了一天的时间把它弄了出来,我也是第一次来做,数据缓存还没有做,如有更好的方法请与我分享。([email protected])
先需求分析一下
UI主线程中初始化ViewFlipper
我是在fragment来做的底部导航,所以我的ViewFlipper在fragment中。
public class FragmentHome extends Fragment {
private ViewFlipper flipper;
private GridView gridView;
private List
将接口的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 imageViews = new ArrayList();
private List 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 stub
this.url = url;
this.handler = handler;
this.flipper = flipper;
this.context = context;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
client = new DefaultHttpClient();
HttpGet request = new HttpGet(); //用GET方法
request.setURI(new URI(url));//设置URL
HttpResponse response = client.execute(request);//发送请求返回响应
HttpEntity entity = response.getEntity();//获得网页内容实体
if(entity != null){
str = EntityUtils.toString(entity);//如果不为空就转换成字符串类型
Log.i("Json", str);
data = parseJson(str);//对获取到的JSON字符串进行解析赋值给List data
for(int i = 0; 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 block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
setVeiwFlipperAnim();//在主线程中更新UI
}
});
super.run();
}
private List parseJson(String json) {
List items = new ArrayList();//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;inew 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 block
e.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;iget(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() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int 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());//传递文章的URL
intent.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文件
<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>
贴下图