为了以后方便使用轮播图,我这里把详细的步骤与代码给出来。
首先布局:
<?xml version="1.0" encoding="utf-8"?>
<!--fitsSystemWindows为true表明为系统视窗留下空间,例如通知栏-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical"
tools:context="com.yangqiangyu.test.carouselview.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
主界面布局,
android.support.design.widget.AppBarLayout里面表示页面头部,可以删除。
ListView是轮播图下面的列表项。
另外的xml就直接创建不用修改,放在layout文件夹里:
carousel_layout.xml
<?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.support.v4.view.ViewPager
android:id="@+id/gallery"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:unselectedAlpha="1">
</android.support.v4.view.ViewPager>
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:gravity="center"
android:layout_gravity="center|bottom"
android:id="@+id/CarouselLayoutPage"
android:padding="10dip">
</LinearLayout>
</FrameLayout>
head_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.yangqiangyu.test.carouselview.CarouselView
android:id="@+id/CarouselView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.yangqiangyu.test.carouselview.CarouselView>
</LinearLayout>
item.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:background="#b0b0b0">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:id="@+id/image" />
</LinearLayout>
另外Java类文件(都是一个包内的):
首先MainActivity.java
package com.yangqiangyu.test.carouselview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private int[] mImagesSrc = {
R.mipmap.img1,
R.mipmap.img2,
R.mipmap.img3,
R.mipmap.img4,
R.mipmap.img5
};
private LayoutInflater mInflater;
private static final String[] strs = new String[] {
"first", "second", "third", "fourth", "fifth","sixth","last"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);// 工具栏(头部)
setSupportActionBar(toolbar);//工具栏(头部)
mInflater = LayoutInflater.from(this);
View headView = mInflater.inflate(R.layout.head_view,null);//获取布局文件转换为view
CarouselView carouselView = (CarouselView)headView.findViewById(R.id.CarouselView);
carouselView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ConvertUtils.dip2px(this,200)));
ListView listView = (ListView) findViewById(R.id.listView);//获取listview的ID
listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, strs));//设置item的内容为strs数组的内容
listView.addHeaderView(carouselView);//把轮播图放在item上面,这里如果你没有使用item那么你就把这里的ID换成你轮播图下面的控件ID
carouselView.setAdapter(new CarouselView.Adapter() {
@Override
public boolean isEmpty() {
return false;
}
@Override
public View getView(int position) {
View view = mInflater.inflate(R.layout.item,null);
ImageView imageView = (ImageView) view.findViewById(R.id.image);
imageView.setImageResource(mImagesSrc[position]);
return view;
}
@Override
public int getCount() {
return mImagesSrc.length;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
其他的一样只导入不用修改:
CarouselView.java
package com.yangqiangyu.test.carouselview;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import java.util.Timer;
import java.util.TimerTask;
/**
*
*/
/**
* user: yangqiangyu on 1/18/16 10:32
* csdn: http://blog.csdn.net/yissan
*/
public class CarouselView extends FrameLayout implements ViewPager.OnPageChangeListener {
private Context context;
private int totalCount =100;
private int showCount;
private int currentPosition =0;
private ViewPager viewPager;
private LinearLayout carouselLayout;
private Adapter adapter;
private int pageItemWidth;
private boolean isUserTouched = false;
private Timer mTimer = new Timer();
private TimerTask mTimerTask = new TimerTask() {
@Override
public void run() {
if (!isUserTouched) {
currentPosition = (currentPosition + 1) % totalCount;
handler.sendEmptyMessage(100);
}
}
};
public void cancelTimer(){
if (this.mTimer!=null){
this.mTimer.cancel();
}
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (currentPosition == totalCount - 1) {
viewPager.setCurrentItem(showCount - 1, false);
} else {
viewPager.setCurrentItem(currentPosition);
}
}
};
public CarouselView(Context context) {
super(context);
this.context = context;
}
public CarouselView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public CarouselView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
}
private void init() {
viewPager.setAdapter(null);
carouselLayout.removeAllViews();
if (adapter.isEmpty()){
return;
}
int count = adapter.getCount();
showCount = adapter.getCount();
for (int i=0;i<count;i++){
View view = new View(context);
if (currentPosition==i){
view.setPressed(true);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth + ConvertUtils.dip2px(context,3),pageItemWidth + ConvertUtils.dip2px(context,3));
params.setMargins(pageItemWidth, 0, 0, 0);
view.setLayoutParams(params);
}else {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth,pageItemWidth);
params.setMargins(pageItemWidth,0,0,0);
view.setLayoutParams(params);
}
view.setBackgroundResource(R.drawable.carousel_layout_page);
carouselLayout.addView(view);
}
viewPager.setAdapter(new ViewPagerAdapter());
viewPager.setCurrentItem(0);
this.viewPager.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
isUserTouched = true;
break;
case MotionEvent.ACTION_UP:
isUserTouched = false;
break;
}
return false;
}
});
mTimer.schedule(mTimerTask, 3000, 3000);
}
public void setAdapter(Adapter adapter){
this.adapter = adapter;
if (adapter!=null){
init();
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
View view = LayoutInflater.from(context).inflate(R.layout.carousel_layout,null);
this.viewPager = (ViewPager) view.findViewById(R.id.gallery);
this.carouselLayout = (LinearLayout)view.findViewById(R.id.CarouselLayoutPage);
pageItemWidth = ConvertUtils.dip2px(context,5);
this.viewPager.addOnPageChangeListener(this);
addView(view);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.d("CarouselView","onPageScrolled was invoke()");
}
@Override
public void onPageSelected(int position) {
currentPosition = position;
int count = carouselLayout.getChildCount();
for (int i = 0;i<count;i++){
View view = carouselLayout.getChildAt(i);
if(position%showCount==i){
view.setSelected(true);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth + ConvertUtils.dip2px(context,3),pageItemWidth + ConvertUtils.dip2px(context,3));
params.setMargins(pageItemWidth, 0, 0, 0);
view.setLayoutParams(params);
}else {
view.setSelected(false);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth,pageItemWidth );
params.setMargins(pageItemWidth, 0, 0, 0);
view.setLayoutParams(params);
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
Log.d("CarouselView","onPageScrollStateChanged was invoke()");
}
class ViewPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return totalCount;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
position %= showCount;
View view = adapter.getView(position);
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
@Override
public void finishUpdate(ViewGroup container) {
super.finishUpdate(container);
int position = viewPager.getCurrentItem();
if (position==0){
position=showCount;
viewPager.setCurrentItem(position,false);
}else if (position==totalCount-1){
position = showCount - 1;
viewPager.setCurrentItem(position,false);
}
}
}
public interface Adapter{
boolean isEmpty();
View getView(int position);
int getCount();
}
}
ConvertUtils.java
package com.yangqiangyu.test.carouselview;
import android.content.Context;
public class ConvertUtils {
public static int dip2px(Context context, float dipValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dipValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(pxValue / scale + 0.5f);
}
}
好了,按照上面的步骤一定行,
图片资源放在mipmap里面。
有问题的欢迎留言,看到一定回答