2015-10-13 31 views
0

當前我正在編程一個android應用程序。我很想在那裏有一個Tab活動,我可以在一個Tab中使用一個片段。我曾試圖按照this教程,但Android Studio中說:在活動+ import語句我的功能在TabActivity中爲一個Tab使用一個片段

Incopatible Types: 
     Required: android.support.v4.app.Fragment 
     Found: de......fragment_nameOfTheFragment 

代碼:

import android.support.design.widget.TabLayout; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentPagerAdapter; 
import android.support.v4.view.ViewPager; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import de.noname.MYNAME.APPNAME.fragment_geocache_details; 
import de.noname.MYNAME.APPNAME.fragment_geocache_details_waypoints; 

@Override 
public Fragment getItem(int position) { 
    switch (position) { 
     case 0: 
      return new fragment_geocache_details_waypoints(); // Here is one fail 
     case 1: 
      return new fragment_geocache_details(); // Here is the other fail 
    } 
} 

如果需要更多的代碼,那麼我將編輯我的帖子。但是我複製了教程中的代碼,並將名稱更改爲我的名稱。

+1

你能發表'de ...... fragment_nameOfTheFragment'的樣本代碼嗎?它是否擴展了'android.support.v4.app.Fragment'? – ThomasThiebaud

回答

1

你不使用正確的進口到de......fragment_nameOfTheFragment

我覺得你有

import android.app.Fragment 

,你需要

import android.support.v4.app.Fragment; 

編輯

@Override 
public Fragment getItem(int position) { 
    Fragment f = null; 
    switch (position) { 
     case 0: 
      f = new fragment_geocache_details_waypoints(); // Here is one fail 
      break; 
     case 1: 
      f = new fragment_geocache_details(); // Here is the other fail 
      break; 
    } 
    return f; 
} 

@Override 
public Fragment getItem(int position) { 
    switch (position) { 
     case 0: 
      return new fragment_geocache_details_waypoints(); // Here is one fail 
     case 1: 
      return new fragment_geocache_details(); // Here is the other fail 
     default: 
      //Do something by default like throw an exception 
    } 
} 
+0

好的,謝謝我已經解決了這個錯誤,感謝您的快速回復,但現在Android Studio聲明返回語句丟失了:( –

+0

請參閱編輯(您的函數需要返回一些東西,它可以爲null,但它必須返回someting如果你喜歡,你可以在你的交換機上添加一個'default'語句) – ThomasThiebaud

+0

ok,Android Studio說沒關係,但是當我嘗試用標籤打開屏幕時,應用程序崩潰,在我的控制檯出現以下失敗代碼: java.lang.NullPointerException:嘗試寫入字段'android.support.v4.app.FragmentManagerImpl android.support.v4.app.Fragment.mFragmentManager'對空對象引用 –

相關問題