简体   繁体   中英

Why doesn't my TabListener work?

I wanted to implement tabs and a tablistener to my app.

    public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        ActionBar.Tab tabA = actionBar.newTab();
        tabA.setText("Tab A");
        tabA.setTabListener(new TabListener<Tab1>(this, "Tag A", Tab1.class));
        actionBar.addTab(tabA);

        Tab tabB = actionBar.newTab();
        tabB.setText("Tab B");
        tabB.setTabListener(new TabListener<Tab2>(this, "Tag B", Tab2.class));
        actionBar.addTab(tabB);

        Tab tabC = actionBar.newTab();
        tabC.setText("Tab C");
        tabC.setTabListener(new TabListener<Tab3>(this, "Tag C", Tab3.class));
        actionBar.addTab(tabC);

        if (savedInstanceState != null) {
            int savedIndex = savedInstanceState.getInt("SAVED_INDEX");
            getActionBar().setSelectedNavigationItem(savedIndex);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putInt("SAVED_INDEX", getActionBar().getSelectedNavigationIndex());
    }

}

But i get an NullPointerException from this line:

actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

Could somebody tell me why and what to do?

I will add the other classes and the StackTrace if needed.

getActionBar() returns null. Do check the manifest if you applied a non action bar theme. If so change the theme so that the activity has actiobar.

public ActionBar getActionBar ()

Added in API level 11 Retrieve a reference to this activity's ActionBar.

Returns The Activity's ActionBar, or null if it does not have one

Which theme are you using? Check if theme is Theme.NoTitleBar in Manifest. If so, change it to ie Theme.Holo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM