0

我有一个BaseFragment所谓的 LeaderboardFragment 扩展Fragment

public class LeaderboardFragment extends Fragment

当我在 中定义下一个时FragmentActivity,我得到类型不匹配:

Fragment[] fragments = new LeaderboardFragment[] {new Fragment1(),
    new Fragment2(), new Fragment3()};

而这些碎片,都在延伸LeaderboardFragment。这样的事情应该是可能的,因为他们只是继承了那个超类。

编辑 这就是我的 FragmentActivity 的样子:

public class LeaderboardTabHost extends FragmentActivity {

ViewPager myViewPager;
Fragment[] fragments = new Fragment[] {new Fragment1(), new Fragment2(), new Fragment3()};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_collection_object);

    MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
    myViewPager = (ViewPager) findViewById(R.id.pager);
    myViewPager.setAdapter(adapter);
    myViewPager.setCurrentItem(1);
}

private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {
        return fragments[index];
    }

    public int getCount() {
        return 3;
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
        ((ViewPager) arg0).removeView((View) arg2);
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        // TODO Auto-generated method stub
        return arg0 == ((View) arg1);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }
}

public class Fragment1 extends LeaderboardFragment {

    public Fragment1() {
        super();
        setTag("time");
    }
}

public class Fragment2 extends LeaderboardFragment {

    public Fragment2() {
        super();
        setTag("distance");
    }
}

public class Fragment3 extends LeaderboardFragment {

    public Fragment3() {
        super();
        setTag("speed");
    }
}

}

确切的错误是:

//Type mismatch: Cannot convert from LeaderboardTabhost.Fragment1 to Fragment
4

2 回答 2

1

我已经解决了这个问题。

android.app.Fragment我在瞄准时不小心延长了android.support.v4.app.Fragment

我修复了导入,错误消失了。

于 2012-06-23T17:18:17.987 回答
0

我认为这行不通。从理论上讲,如果您将片段定义为Fragment[]并使用 对其进行初始化LeaderboardFragment[],那么将其他类型的片段添加到该数组Fragment中会发生什么?LeaderboardFragment

无论如何,我不明白为什么你不能使用这个:

Fragment[] fragments = new Fragment[] {new Fragment1(),
new Fragment2(), new Fragment3()};

最后,数组中的对象是扩展类的类的实例Fragment

于 2012-06-23T16:50:06.490 回答