码迷,mamicode.com
首页 > 其他好文 > 详细

记录一波三折的ViewPager与PagerAdapter

时间:2015-07-07 19:04:56      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

本来很简单的一个东西弄了几个小时,好吧记录一下遇到的种种问题,以便以后出现同样的错误可以迅速解决

ViewPager是android3.0中新加的一个组件,用来右滑动切换多个View,这东西很适合做启动页面与导航页面之类的东西.

要使用ViewPager首先需要做如下事情:

1.导入android-support-v4.jar

2.一个包含ViewPager的布局文件

3.最后制作一个每个切换的View的Layout文件,infalte起来比较方便(可选)

4.实现一个Adapter 继承与 PagerAdapter  ,在instantiateItem方法中生成View,并将这个view添加到container中 . container.addView(v)

 

PagerAdapter必须实现如下方法: (带星号的是必须实现的方法)

* public int getCount() 获取总View的数量

public void startUpdate(ViewGroup container) 

* public Object instantiateItem(ViewGroup container, int position)   实例化当前的View,添加到contrainer中,然后返回生成的View或关联的Object (用于在isViewFromObject中检查)

* public void destroyItem(ViewGroup container, int position, Object object)  从container中移除指定的View (释放内存)

public void finishUpdate(ViewGroup container) 

* public boolean isViewFromObject(View view, Object object) 检查View是否与一个Object关联,

 

在开发过程中遇到很多问题总结如下:

1.通过gradle 添加编译依赖包 ,由两种方式可以添加

(第一种导入方式)通过jar包放入到lib目录下,然后添加


compile fileTree(dir: ‘libs‘, include: [‘*.jar‘])
compile ‘com.android.support:android-support-v7-appcompat‘
compile ‘com.android.support:android-support-v4‘

(第二种导入方式)通过sdk目录下 android-sdk-linux/extras/android/m2repository/com/android/support/support-v4/ 目录下对应的版本导入

compile ‘com.android.support:support-v4:22.2.0‘
compile ‘com.android.support:appcompat-v7:22.2.0‘

导入完整后编译总是提示

Unable to start activity ComponentInfo{linuxeye.com.knowledgeispower/linuxeye.com.knowledgeispower.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)‘ on a null object reference

开始以为是因为包没有导入,到处google,bing,baidu, 看到一片stackoverflow上的问答,说是Activity没有生成,突然间想到是不是Activity的代码有问题.

经过反复调试,发现findViewById竟然在setViewContent之前被调用,导致findViewById一致返回null引起的.我靠这个错误的代价是一个小时!这个一个小时反复的清理项目从新导入包..反复的检查问题.

之间还想过是不是ViewPager的布局外面需要一个Layout之类的.真的是累死人了.ViewPager是不需要外容器的,可以直接作为Layout使用的.

布局文件如下 . mypager.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.view.ViewPager
android:id="@+id/my_pager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</android.support.v4.view.ViewPager>


修改完Activity后可以findViewById了,接下来的问题就是Activity确实显示出来了,就是什么内容都没有,一片漆黑呀!
这个过程也是浪费了我好长时间,反复baidu看别人的代码和文章,发现一个问题,我的isViewFromObject方法是android Studio自动生成的,代码自动返回false,看到文档里写着这个方法是用来比较View和Object是否有关联
?

这个方法是在ViewPager中被调用的,ViewPager将每一个View添加到mItems中,mItem是一个ArrayList<ItemInfo> , ItemInfo是每个View相关的信息,其中Object就是 instantiateItem 方法返回的哪个Object,
官方文档标注这个对象可以不是一个View,是用来让ViewPager检查是否和一个View对应的. 
 
static class ItemInfo {
Object object;
int position;
boolean scrolling;
float widthFactor;
float offset;
}


修改了isViewFromObject方法为:
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
一切都ok了,图片终于显示出来了!大工告成!



AppPagerAdapter代码如下:
package linuxeye.com.knowledgeispower;

import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;

import java.util.ArrayList;


/**
* Created by Raffeale on 15-7-7.
*/
public class AppPagerAdapter extends PagerAdapter {

Context ctx = null;
ArrayList<ImageView> pagerData = null;

public AppPagerAdapter(Context ct , ArrayList<ImageView> data) {

ctx = ct;
pagerData = data;

}

/**
* Return the number of views available.
*/
@Override
public int getCount() {
return pagerData.size();
}




/**
* Create the page for the given position. The adapter is responsible
* for adding the view to the container given here, although it only
* must ensure this is done by the time it returns from
* {@link #finishUpdate(ViewGroup)}.
*
* @param container The containing View in which the page will be shown.
* @param position The page position to be instantiated.
* @return Returns an Object representing the new page. This does not
* need to be a View, but can be some other container of the page.
*/
@Override
public Object instantiateItem(ViewGroup container, int position) {
Log.i("PagerAdapter" , "method instantiateItem be calling" );
View v = LayoutInflater.from(ctx).inflate(R.layout.pager , null);
ImageView img = (ImageView) v.findViewById(R.id.page_img);
img.setImageResource(R.drawable.pic0+position);
if(position+1 == pagerData.size()) {
ImageButton ib = (ImageButton)v.findViewById(R.id.ib);
ib.setVisibility(View.VISIBLE);
ib.setBackgroundResource(R.drawable.bt);
ib.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ctx.startActivity(new Intent(ctx,ArticleActivity.class));
}
});
}

container.addView(v);
return v;


//return super.instantiateItem(container, position);
}

/**
* Remove a page for the given position. The adapter is responsible
* for removing the view from its container, although it only must ensure
* this is done by the time it returns from {@link #finishUpdate(ViewGroup)}.
*
* @param container The containing View from which the page will be removed.
* @param position The page position to be removed.
* @param object The same object that was returned by
* {@link #instantiateItem(View, int)}.
*/
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
Log.i("PagerAdapter" , "method destroyItem be calling");
container.removeView((View)object);
}

/**
* Determines whether a page View is associated with a specific key object
* as returned by {@link #instantiateItem(ViewGroup, int)}. This method is
* required for a PagerAdapter to function properly.
*
* @param view Page View to check for association with <code>object</code>
* @param object Object to check for association with <code>view</code>
* @return true if <code>view</code> is associated with the key object <code>object</code>
*/
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}



}




Activity代码如下:


package linuxeye.com.knowledgeispower;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.widget.ImageView;

import java.util.ArrayList;


public class MainActivity extends Activity {
ViewPager vp = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//vp = new ViewPager(this);
setContentView(R.layout.activity_main);
ArrayList<ImageView> data = new ArrayList<ImageView>();
for(int i=0;i<5;i++) {
ImageView img = new ImageView(this);
img.setImageResource(R.drawable.pic0+i);
data.add(img);
}


AppPagerAdapter myadapter = new AppPagerAdapter(this , data);

vp = (ViewPager)findViewById(R.id.my_pager);

//LayoutInflater inflater = getLayoutInflater();
try{

vp.setAdapter(myadapter);
}catch (Exception ex) {
ex.printStackTrace();
}


}

}
 


记录一波三折的ViewPager与PagerAdapter

标签:

原文地址:http://www.cnblogs.com/raffeale/p/android.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!