2015-04-11 16 views
6

Ich habe ein Android-Beispielprojekt namens HorizontalPaging in Android Studio importiert und es funktioniert einwandfrei, wenn ich es ausführe. Aber wenn ich den Code in meinen Code kopierte, bekomme ich eine NULL-Zeiger-Ausnahme in getActionBar().Android FragmentActivity gibt null in getActionBar() zurück

Ich habe den ganzen Tag über diese Probleme gelesen, kann aber nicht funktionieren. Ich habe versucht, den gesamten Code aus der MainActivity des Samples in mein Projekt zu kopieren, aber keine Verbesserungen, daher vermute ich, dass das Problem in einer anderen Datei wie Manifest, Styles, etc.

MainActivity.java aus dem Beispielprojekt

import android.app.ActionBar; 
import android.app.FragmentTransaction; 
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.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.TextView; 

import java.util.Locale; 


public class View_Tabs extends FragmentActivity implements ActionBar.TabListener { 


SectionsPagerAdapter mSectionsPagerAdapter; 


ViewPager mViewPager; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    // Load the UI from res/layout/activity_main.xml 
    setContentView(R.layout.view_tabs); 


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


    // Create the adapter that will return a fragment for each of the three primary sections 
    // of the app. 
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager) findViewById(R.id.pager); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    // When swiping between different sections, select the corresponding tab. We can also use 
    // ActionBar.Tab#select() to do this if we have a reference to the Tab. 

    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
     @Override 
     public void onPageSelected(int position) { 
      actionBar.setSelectedNavigationItem(position); 
     } 
    }); 



    // For each of the sections in the app, add a tab to the action bar. 
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { 
     // Create a tab with text corresponding to the page title defined by the adapter. Also 
     // specify this Activity object, which implements the TabListener interface, as the 
     // callback (listener) for when this tab is selected. 
     actionBar.addTab(
       actionBar.newTab() 
         .setText(mSectionsPagerAdapter.getPageTitle(i)) 
         .setTabListener(this)); 
    } 

} 


@Override 
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
    // When the given tab is selected, tell the ViewPager to switch to the corresponding page. 
    mViewPager.setCurrentItem(tab.getPosition()); 
} 



@Override 
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
} 


@Override 
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
} 


public class SectionsPagerAdapter extends FragmentPagerAdapter { 


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



    @Override 
    public Fragment getItem(int position) { 
     // getItem is called to instantiate the fragment for the given page. 
     // Return a DummySectionFragment (defined as a static inner class 
     // below) with the page number as its lone argument. 
     Fragment fragment = new DummySectionFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1); 
     fragment.setArguments(args); 
     return fragment; 
    } 


    @Override 
    public int getCount() { 
     // Show 3 total pages. 
     return 3; 
    } 


    @Override 
    public CharSequence getPageTitle(int position) { 
     Locale l = Locale.getDefault(); 
     switch (position) { 
      case 0: 
       return getString(R.string.tab_list).toUpperCase(l); 
      case 1: 
       return getString(R.string.tab_map).toUpperCase(l); 
      case 2: 
       return getString(R.string.tab_list).toUpperCase(l); 
     } 
     return null; 
    } 

} 

/** 
* A dummy fragment representing a section of the app, but that simply displays dummy text. 
* This would be replaced with your application's content. 
*/ 
public static class DummySectionFragment extends Fragment { 
    /** 
    * The fragment argument representing the section number for this 
    * fragment. 
    */ 
    public static final String ARG_SECTION_NUMBER = "section_number"; 

    public DummySectionFragment() { 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.list_tab_fragment, container, false); 
     TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label); 
     dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER))); 
     return rootView; 
    } 
} 



} 

mein Manifest

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 

<!-- TABS: While ViewPager will work on API 4 or above, tabs require an ActionBar. ActionBar is only 
available in API 11 or above. --> 
<!-- Min/target SDK versions (<uses-sdk>) managed by build.gradle --> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 



    <meta-data android:name="com.google.android.gms.version" 
     android:value="@integer/google_play_services_version" /> 

    <!-- 
    <meta-data android:name="com.google.android.gms.version" 
     android:value="@integer/google_play_services_version" /> 
    --> 

    <meta-data 
     android:name="com.google.android.maps.v2.API_KEY" 
     android:value="xxxxx"/> 

    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" 
     android:screenOrientation="portrait" 
     > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

.... 

    <activity 
     android:name=".View_Tabs" 
     android:label="@string/app_name" 
     android:screenOrientation="portrait" 
     > 
    </activity> 
</application> 

styles.xml meine kopiert

<resources> 

    <!-- Base application theme. --> 
    <!-- BEFORE <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> --> 
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> 
     <!-- Customize your theme here. --> 
     <item name="android:windowActionBar">true</item> 
    </style> 

    <style name="Theme.Base" parent="android:Theme.Light" /> 




</resources> 

mein gradle

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 21 
    buildToolsVersion "21.1.2" 

    defaultConfig { 
     applicationId "xxxx" 
     minSdkVersion 14 
     targetSdkVersion 21 
     versionCode 1 
     versionName "1.0" 
    } 
    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    compile 'com.android.support:appcompat-v7:21.0.3' 
    compile 'com.google.android.gms:play-services:6.5.87' 
    //compile 'com.google.android.gms:play-services:7.0.0' 
    compile files('lib/gson-2.3.jar') 
} 
+0

Ausprobieren: 'final ActionBar ActionBar = getActionBar();' dazu: 'letzte ActionBar ActionBar = getSupportActionBar();' – Josef

+0

verwenden getSupportActionBar() Ich brauchte FragmentActivity zu ActionBarActivity sonst das Casting zu ActionBarActivity ändern gibt mir Cast-Ausnahmefehler. Und ändern Sie auch Import android.app.ActionBar, um android.support.v7.app.ActionBar zu importieren. Auf diese Weise läuft die App in Ordnung, aber ich verstehe immer noch nicht, warum der Beispielcode NUR außerhalb meines Projekts einwandfrei funktioniert. Danke für die Hilfe! – fersarr

Antwort

8

Sie müssen ActionBarActivity anstelle von FragmentActivity erweitern, um Actionbar mit Fragmenten zu haben.

Wenn Sie die Appcompat-Bibliothek v7 verwenden, sollte Ihre Aktivität stattdessen ActionBarActivity erweitern, eine Unterklasse von FragmentActivity (weitere Informationen finden Sie unter Hinzufügen der Aktionsleiste).

Noch können Sie dies versuchen,

ActionBar actionBar = (ActionBarActivity)getActivity().getSupportActionBar(); 

Weitere Details, die Sie hier finden kann. diese Veränderung http://developer.android.com/training/basics/fragments/creating.html

1

getActionBar() wird richtigen Wert zurück, wenn Sie die Aktivität mit einer Titelleiste haben. Stellen Sie sicher, dass Sie in Ihrer Manifestdatei ein Thema mit Titelleiste für Ihre Aktivität festgelegt haben.

Verwandte Themen