按下开始按钮后,我正在尝试开始播放幻灯片。我在这里看到了一些使用ViewPager和PagerAdapter的例子,但它们似乎都没有帮助。我的代码如下。当我按下开始按钮时,我的logCat说有一个nullPointerException。
公共类MainActivity扩展了Activity {
private ViewPager mViewPager;
private SwipeAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startShow(View v) {
Toast toast = Toast.makeText(this, "Button was Clicked!", Toast.LENGTH_LONG);
toast.show();
mViewPager = (ViewPager) findViewById(R.id.pager);
adapter = new SwipeAdapter(MainActivity.this);
mViewPager.setAdapter(adapter);
}
private class SwipeAdapter extends PagerAdapter {
private LayoutInflater mInflater;
private int[] mLayouts = {R.layout.layout1, R.layout.layout2, R.layout.layout3, R.layout.layout4};
public SwipeAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ViewGroup pageView = (ViewGroup) mInflater.inflate(mLayouts[position],
container, false);
container.addView(pageView);
getItemPosition(pageView);
return pageView;
}
@Override
public int getCount() {
return mLayouts.length;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
}
我的按钮包含一个正常工作的onClick属性。我的4个布局文件包含ImageViews,其中包含幻灯片显示的4张图片(已定义:R.layout.layout1等...)。我有一个简单定义ViewPager的寻呼机xml文件。有什么建议吗?
答案 0 :(得分:0)
您收到NullPointerException,因为您正在引用不在activity_main中的寻呼机。在View_main中放置您的ViewPager
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
最好将视图的实例化从startShow()
移到onCreateprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
adapter = new SwipeAdapter(MainActivity.this);
mViewPager.setAdapter(adapter);
}