轮播图Viewpager支持手动滑动定时滑动和自动加载图片页数

来源:互联网 发布:淘宝棋牌游戏源码 编辑:程序博客网 时间:2024/05/16 07:16
首先来分析布局结构吧


外面是个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;@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.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("郁闷。。网络有问题");}}};@Overrideprotected 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 stubinitView();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() {@Overridepublic boolean onTouch(View arg0, MotionEvent arg1) {// TODO Auto-generated method stubif(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 stubfor (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 stubfor (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 stubStringRequest request = new StringRequest(Request.Method.GET ,url, new Listener<String>() {private String str;@Overridepublic void onResponse(String response) { try { byte[] bytes = response.getBytes();  str = new String(bytes, "gb2312"); } catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.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() {@Overridepublic 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 stubif(title == null)return "";else return title;}}adapterpublic 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);}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn bannerLsit != null ? bannerLsit.size() : 0;}@Overridepublic boolean isViewFromObject(View arg0, Object arg1) {// TODO Auto-generated method stubreturn arg1 == arg0;}@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {// TODO Auto-generated method stub   container.removeView((View) object);}@Overridepublic int getItemPosition(Object object) {// TODO Auto-generated method stubreturn POSITION_NONE;}@Overridepublic 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;}@Overridepublic void unregisterDataSetObserver(DataSetObserver observer) {// TODO Auto-generated method stubsuper.unregisterDataSetObserver(observer);}@Overridepublic void notifyDataSetChanged() {// TODO Auto-generated method stubsuper.notifyDataSetChanged();}@Overridepublic void registerDataSetObserver(DataSetObserver observer) {// TODO Auto-generated method stubsuper.registerDataSetObserver(observer);}@Overridepublic void finishUpdate(ViewGroup container) {// TODO Auto-generated method stubsuper.finishUpdate(container);}}








0 0
原创粉丝点击