0

我在这段代码中遇到了一些问题:

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

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

4

1 回答 1

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);
于 2013-02-03T00:24:34.237 回答