PageViewer加载空白视图...未调用getItem()

时间:2014-08-12 20:24:16

标签: android android-viewpager fragment android-fragmentactivity layout-inflater

我正在尝试使用viewpager创建水平滚动布局。应用程序运行时没有错误,但是当设置了activitymain布局并且设置了viewpager的适配器时,应用程序只显示一个空白屏幕。在使用Log.d()进行一些调试后,我发现我的适配器类中的getItem()方法没有被调用,我怀疑是问题。

我无法解决这个问题,请查看下面的代码并提供帮助,谢谢大家。

Main Activity Code:

package myapp.pkg;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;

public class MainActivity extends FragmentActivity
{

    ViewPager viewpager = null;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("Debug","content set");

        viewpager = (ViewPager) findViewById(R.id.mainpager);

        FragmentManager fgm = getSupportFragmentManager();

        viewpager.setAdapter(new VPAdapt(fgm));
        Log.d("Debug","adapt set");

    }
}

页面查看器适配器

package myapp.pkg;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;

class VPAdapt extends FragmentPagerAdapter 
    {
        public VPAdapt (FragmentManager fm)
        {
            super(fm);
            Log.d("Debug","VPAdapt called");
        }

        public Fragment getItem(int i)
        {
            Log.d("Debug","VPAdapt getItem called i = " + i);

            Fragment frag = null;

            if(i == 0)
            {
                frag = new HomeT();
                Log.d("Debug","HomeT set");
            }
            if(i == 1)
            {
                frag = new NewsT();
                Log.d("Debug","HomeN set");
            }
            if(i == 2)
            {
                frag = new FeatT();
                Log.d("Debug","HomeF set");
            }

            return null;
        }
        @Override
        public int getCount()
        {
            return 0;
        }

    }

其中一个片段类

package myapp.pkg;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class HomeT extends Fragment
{

    @Override
    public View onCreateView(LayoutInflater inf, ViewGroup vg, Bundle savedInstanceState )
    {

        return inf.inflate(R.layout.hometitle, vg, false);
    }


}

1 个答案:

答案 0 :(得分:1)

<强>问题:

@Override
    public int getCount()
    {
        return 0;
    }

它加载空白,因为您指定的片段数为0。

<强>溶液

返回ViewPagers的getCount中的片段编号,而不是0

@Override
public int getCount()
{
   return 3;
}