0

我试图在带有标签的android中制作一个基本的用户界面。但是,每当我尝试运行它时,我都会收到一个空指针异常。该错误源于初始化 viewpager。(我不知道还要输入什么,每当我尝试发布时我都会收到错误消息。)

public class MainActivity extends FragmentActivity implements TabListener {
ActionBar actionBar;
ViewPager viewPager;

@Override
protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);
    setContentView(R.layout.activity_main);

    viewPager=(ViewPager) viewPager.findViewById(R.id.tabs);
    viewPager.setAdapter(new adapter(getSupportFragmentManager()));
    actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    ActionBar.Tab stocks = actionBar.newTab();
    stocks.setText("Stocks");
    stocks.setTabListener(this);

    ActionBar.Tab market = actionBar.newTab();
    market.setText("Market");
    market.setTabListener(this);

    ActionBar.Tab portfolio = actionBar.newTab();
    portfolio.setText("Portfolio");
    portfolio.setTabListener(this);

    actionBar.addTab(stocks);
    actionBar.addTab(market);
    actionBar.addTab(portfolio);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.mainsearch, menu);
    return true;
}



@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub

}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub

}

class adapter extends FragmentPagerAdapter {

    public adapter(FragmentManager fm) {
        super(fm);
        // TODO Auto-generated constructor stub
    }

    public Fragment getItem(int arg0) {
        Fragment fragment = null;
        if(arg0==0) {
            fragment = new StocksFragment();
        }
        if (arg0==1){
            fragment = new MarketFragment();
        }
        if (arg0==2){
            fragment = new PortfolioFragment();
        }
        return fragment;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return 3;
    }
}

}

4

2 回答 2

1

当然,这条线会给出一个NPE

 viewPager=(ViewPager) viewPager.findViewById(R.id.tabs);

您正在尝试初始化的对象上调用方法(调用findViewById()null viewPager

如果tabs在,activity_main.xml那么只需删除viewPager

viewPager=(ViewPager) findViewById(R.id.tabs);
于 2013-11-07T20:38:31.813 回答
-1

findViewById 是活动的方法,而不是视图的方法。所以应该是:

viewPager=(ViewPager) this.findViewById(R.id.tabs);
于 2013-11-07T20:39:11.310 回答