輪播圖在項目開發中也是屬于比較常見的UI實現,一般會采用ViewPager來實現,今天的博客我就不再隨大流了,給大家介紹個簡單的 實現方式,在此方式下你只需做簡單的配置即可。下面有通過代碼來帶著大家一起來實現下這個簡單的UI效果。
由于我介紹的這個輪播圖是利用給View或者繼承view的其他控件定期更換背景來實現的,所以在布局文件中,自然少不了這么一個View或者其子類(TextView,Imageview)等
布局
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <!--***********顯示輪播圖的View*************--> <TextView android:id="@+id/header_layout" android:layout_width="match_parent" android:layout_height="110dp" android:background="@drawable/xycz_news_img_2" /> <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/swipe_refresh" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/listView" android:dividerHeight="2dp" android:padding="5dp" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.v4.widget.SwipeRefreshLayout> </LinearLayout><include layout="@layout/load_animation"/></FrameLayout>在java代碼中自定義一個Runnable類繼承自Runnable,通過handler發送延時消息
PRivate int imgsRes [] = {R.drawable.xycz_news_img_1,R.drawable.xycz_news_img_2,R.drawable.xycz_news_img_3}; //輪播的圖片資源 private int imgIndex; //當前imgRes的角標索引 private MyRunable myRunable = new MyRunable(); class MyRunable implements Runnable { @Override public void run() { imgIndex++; imgIndex=imgIndex%3; ((TextView) view.findViewById(R.id.header_layout)).setBackgroundResource(imgsRes[imgIndex]); mHandler.postDelayed(myRunable,3000); } }在Java類的入口方法(onCreate、onCreateView)讓該Runnable對象跑起來mHandler.postDelayed(myRunable,3000); //通知線程更新輪播圖當然還需要有個Handler對象。到此為止整個功能就簡單實現了,個人感覺在需求不是太苛刻時,用此方法比ViewPager要簡單很多,可以省去很多繁瑣的代碼
新聞熱點
疑難解答