Android MyAdapter不能是静态的

时间:2013-02-03 00:15:45

标签: android android-fragments android-viewpager android-adapter

我对这段代码遇到了一些麻烦:

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);

显然我做错了什么,但我找不到它。

1 个答案:

答案 0 :(得分:2)

首先,不,static类仅用于内部类,其中内部类的实例不应该绑定到外部类的实例。 (也就是说,在外部类中,不应使用已修改的static。)

其次,空指针位于语句myViewPager.setAdapter(myAdapter);中,正如您推断的那样,意味着myViewPager为空。因此,findViewById()返回null(找不到项目):

myViewPager = (ViewPager) findViewById(R.id.pager);

注意,在您的XML中:android:id="@+id/view_pager"。上面的那一行应该是:

myViewPager = (ViewPager) findViewById(R.id.view_pager);