我在这段代码中遇到了一些问题:
MyAdapter.java:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return 3;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: return new SpeedZonesFragment();
case 1: return new DistanceFragment();
case 2: return new FuelConsumptionFragment();
default: return null;
}
}
}
MainActivity.java:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
private MyAdapter myAdapter;
private ViewPager myViewPager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager);
myAdapter = new MyAdapter(getSupportFragmentManager());
myViewPager = (ViewPager) findViewById(R.id.pager);
myViewPager.setAdapter(myAdapter);
view_pager.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:orientation="vertical" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/view_pager" />
</LinearLayout>
我的问题是,我能找到的每个示例都将 MyAdapter 声明为public static class
但是Eclipse
会引发错误:Illegal modifier for the class MyAdapter; only public, abstract & final are permitted
。
如果我尝试在没有返回静态的情况下运行我的代码(来自 LogCat):
Caused by: java.lang.NullPointerException
02-02 23:13:26.076: E/AndroidRuntime(928):
at simcas.fartberegneren.MainActivity.onCreate(MainActivity.java:23)
编辑:第 23 行是行myViewPager.setAdapter(myAdapter);
显然我做错了什么,但我找不到它。