轮播图Viewpager支持手动滑动定时滑动和自动加载图片页数
2016-04-07 15:41
423 查看
首先来分析布局结构吧
外面是个FrameLayout 因为文字需要覆盖在image上面
接下来就是引入
android.support.v4.view.ViewPager
下面的文字和点用线性布局
main_layout
对了还有个点样式
GSON 顺便提一下
比如json字符串为:[{"name":"name0","age":0}]
代码:
提供两个参数,分别是json字符串以及需要转换对象的类型。
第二种,转换成列表类型:
代码:
那么开始步入主题了
分析
实现滑动用到适配器pageradapter
实现定时切换 可以用到handler定时发送消息 和timer定时器,等,这里我们就用handler
还有一点,就是当滑到第一个还要向左滑动,让它切换到到最后一个,如何处理?同理最后 一个pager
这里加载网络就用volley吧,为了方便因为这不是我们的重点
好了,上代码
外面是个FrameLayout 因为文字需要覆盖在image上面
接下来就是引入
android.support.v4.view.ViewPager
下面的文字和点用线性布局
main_layout
<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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <FrameLayout android:id="@+id/fl" android:layout_width="fill_parent" android:layout_height="wrap_content"> <android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="190dp"/> <LinearLayout android:layout_marginTop="145dp" android:gravity="center_vertical" android:background="#66000000" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="45dp"> <TextView android:id="@+id/title" android:text="abcdefg ,hijklmn,opqrdt" android:textColor="#ffffff" android:maxLines="2" android:ellipsize="end" android:lineSpacingMultiplier="1.2" android:gravity="center_vertical" android:layout_marginLeft="5dp" android:layout_weight="5" android:layout_width="0dp" android:layout_height="match_parent" /> <LinearLayout android:id="@+id/dot_ll" android:layout_weight="3" android:orientation="horizontal" android:gravity="end|bottom" android:padding="9dp" android:layout_width="0dp" android:layout_height="match_parent"> </LinearLayout> </LinearLayout> </FrameLayout> <ImageView android:layout_below="@id/fl" android:id="@+id/iv" android:scaleType="center" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout>
对了还有个点样式
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <solid android:color="#ffffff"/> <corners android:radius="6dp"/> </shape> shape 形状 solid 线的 颜色 corners 半径
GSON 顺便提一下
比如json字符串为:[{"name":"name0","age":0}]
代码:
Person person = gson.fromJson(str, Person.class);
提供两个参数,分别是json字符串以及需要转换对象的类型。
第二种,转换成列表类型:
代码:
List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType()); for(int i =0; i < ps.size() ; i++) { Person p = ps.get(i); System.out.println(p.toString()); }
那么开始步入主题了
分析
实现滑动用到适配器pageradapter
实现定时切换 可以用到handler定时发送消息 和timer定时器,等,这里我们就用handler
还有一点,就是当滑到第一个还要向左滑动,让它切换到到最后一个,如何处理?同理最后 一个pager
这里加载网络就用volley吧,为了方便因为这不是我们的重点
好了,上代码
public class MainActivity extends Activity { private static final String url = "http://news-at.zhihu.com/api/4/news/latest"; private static final int MSG = 0x10 ; private static final int MSG_SCROLL = 1; private static final int Defalut_postion= 100; private static final int isError = 10000; private boolean isScroll = true ; private BannerAdapter bannerAdapter; protected int mBannerPosition = 0; private ImageView [] imgs; private TextView tv_title; private ViewPager pager; private LinearLayout ll_dots; public ImageLoader imageLoader = ImageLoader.getInstance(); @Override public boolean onCreateOptionsMenu(Menu menu) { //Added in the code by me for handling the init error imageLoader.init(ImageLoaderConfiguration.createDefault(getBaseContext())); return true; } private Handler handler = new Handler(){ private ItemText infoBean; private List<Story> storyList; @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); if (msg.what == MSG) { infoBean = (ItemText) msg.obj; storyList = infoBean.stories; if(storyList.size() > 0 && storyList != null){ initAfterView(storyList); }else{ tv_title.setText("郁闷。。网络有问题"); } } if (msg.what == MSG_SCROLL) { Log.i("mBannerPosition","位置="+mBannerPosition); if(isScroll){ int max = infoBean.stories.size(); Log.i("max","位置="+max); int position = (mBannerPosition + 1) % Defalut_postion; if (position == max) { // 最后一页时回到第一页 pager.setCurrentItem(0, false); }else{ Log.i("cuurrent","位置="+position); pager.setCurrentItem(position); } if(storyList != null || storyList.size() == 0){ setTitle(storyList); }else{ tv_title.setText("郁闷。。网络有问题"); } handler.removeMessages(MSG_SCROLL); handler.sendEmptyMessageDelayed(MSG_SCROLL, 2000); } } if(msg.what == isError){ tv_title.setText("郁闷。。网络有问题"); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView iv = (ImageView) findViewById(R.id.iv); BitmapUtils mBitmapUtils = new BitmapUtils(this); //mBitmapUtils.display(iv, "http://pic1.zhimg.com//6387f9f8cafb0719c15067a7f5659474.jpg"); init(); } private void init() { // TODO Auto-generated method stub initView(); initData(); handler.sendEmptyMessageDelayed(MSG_SCROLL, 2000); initEvent(); } private void initEvent() { pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mBannerPosition = position; setIndicator(position); } @Override public void onPageScrollStateChanged(int state) { } }); pager.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { // TODO Auto-generated method stub if(arg1.getAction() == MotionEvent.ACTION_UP){ isScroll = true ; handler.sendEmptyMessageDelayed(MSG_SCROLL, 2000); }else { isScroll = false ; } return false; } }); } protected void setTitle2(int position) { // TODO Auto-generated method stub } protected void setIndicator(int position) { // TODO Auto-generated method stub for (ImageView img : imgs) { img.setBackgroundResource(R.drawable.dot_normal); } imgs[position].setBackgroundResource(R.drawable.dot_focused); } private void initView() { pager = (ViewPager) findViewById(R.id.view_pager); ll_dots = (LinearLayout) findViewById(R.id.dot_ll); tv_title = (TextView) findViewById(R.id.title); } private void initDotas(List<Story> storyList) { imgs = new ImageView[storyList.size()]; // TODO Auto-generated method stub for (int i = 0; i < storyList.size(); i++) { ImageView img = new ImageView(this); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(6,6); params.rightMargin = 8; img.setLayoutParams(params); img.setBackgroundResource(R.drawable.dot_normal); ll_dots.addView(img, params); imgs[i] = img; } } // return jsonstr.substring(jsonstr.indexOf("{")).replace("\r\n","\n"); private void initData() { Volley volley = new Volley(); RequestQueue queue = volley.newRequestQueue(this); // TODO Auto-generated method stub StringRequest request = new StringRequest(Request.Method.GET ,url, new Listener<String>() { private String str; @Override public void onResponse(String response) { try { byte[] bytes = response.getBytes(); str = new String(bytes, "gb2312"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(str != null){ ItemText infoBean = new Gson().fromJson(str,ItemText.class ); Log.i("response", response); Message message = new Message(); message.obj = infoBean; message.what = MSG; handler.sendMessage(message); }else{ Message message = new Message(); message.what = isError; handler.sendMessage(message); } } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub } }); queue.add(request); } private void initAfterView(List<Story> storyList) { bannerAdapter = new BannerAdapter(this ,storyList); pager.setAdapter(bannerAdapter); initDotas(storyList); setTitle(storyList); } private void setTitle(List<Story> storyList) { tv_title.setText(""+check(storyList.get(mBannerPosition).title)); Log.i("mBannerPositionsetTitle==", "=="+mBannerPosition); Log.i("storyList.get(mBannerPosition).title", "=="+storyList.get(mBannerPosition).title); } private String check(String title) { // TODO Auto-generated method stub if(title == null) return ""; else return title; } } adapter public class BannerAdapter extends PagerAdapter { private List<Story> bannerLsit; private Context mContext ; private BitmapUtils mBitmapUtils; public BannerAdapter(Context mContext ,List<Story> storyList){ this.mContext = mContext; this.bannerLsit = storyList; mBitmapUtils = new BitmapUtils(mContext); } @Override public int getCount() { // TODO Auto-generated method stub return bannerLsit != null ? bannerLsit.size() : 0; } @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return arg1 == arg0; } @Override public void destroyItem(ViewGroup container, int position, Object object) { // TODO Auto-generated method stub container.removeView((View) object); } @Override public int getItemPosition(Object object) { // TODO Auto-generated method stub return POSITION_NONE; } @Override public Object instantiateItem(ViewGroup container, int position) { // TODO Auto-generated method stub View view = LayoutInflater.from(mContext).inflate(R.layout.item, container, false); ImageView iv = (ImageView) view.findViewById(R.id.image); String abc = bannerLsit.get(position).images.get(0); mBitmapUtils.display(iv,bannerLsit.get(position).images.get(0)); container.addView(view); return view; } @Override public void unregisterDataSetObserver(DataSetObserver observer) { // TODO Auto-generated method stub super.unregisterDataSetObserver(observer); } @Override public void notifyDataSetChanged() { // TODO Auto-generated method stub super.notifyDataSetChanged(); } @Override public void registerDataSetObserver(DataSetObserver observer) { // TODO Auto-generated method stub super.registerDataSetObserver(observer); } @Override public void finishUpdate(ViewGroup container) { // TODO Auto-generated method stub super.finishUpdate(container); } }
相关文章推荐
- 屏幕录制
- 44、如何修改已经创建好的数据库的编码格式
- leetcode189.RotateArray
- 6.9.4 qmgr_active_done_25_generic函数:发送退信或延迟提醒信
- mysql innodb 优化 参数篇
- Android自定义绘制
- JPA Many To Many Duplicate record in join table
- 一个函数看懂View事件分发机制
- activiti自定义流程之Spring整合activiti-modeler5.16实例(九):历史任务查询
- R 语言笔记 频数表和列联表
- 在网页中使用SVG技术
- Xcode 运行项目时候选择模拟器位置处显示"My Mac" 的处理
- activiti自定义流程之Spring整合activiti-modeler5.16实例(九):历史任务查询
- vs2012 使用正则查找和替换
- UITableView优化技巧
- 脚本编译安装DRBD
- web.xml中load-on-startup的作用
- 一个实现 Twitter SnowFlake 算法 的 Go 分布式 UID 生成器
- 学习笔记一
- 6.9.3 qmgr_active_done_2_generic函数:发送邮件状态通知信