在TabActivity中为一个Tab使用一个片段
当前我正在编程一个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
}
}
如果需要更多的代码,那么我将编辑我的帖子。但是我复制了教程中的代码,并将名称更改为我的名称。
你不使用正确的进口到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
}
}
好的,谢谢我已经解决了这个错误,感谢您的快速回复,但现在Android Studio声明返回语句丢失了:( –
请参阅编辑(您的函数需要返回一些东西,它可以为null,但它必须返回someting如果你喜欢,你可以在你的交换机上添加一个'default'语句) – ThomasThiebaud
ok,Android Studio说没关系,但是当我尝试用标签打开屏幕时,应用程序崩溃,在我的控制台出现以下失败代码: java.lang.NullPointerException:尝试写入字段'android.support.v4.app.FragmentManagerImpl android.support.v4.app.Fragment.mFragmentManager'对空对象引用 –
你能发表'de ...... fragment_nameOfTheFragment'的样本代码吗?它是否扩展了'android.support.v4.app.Fragment'? – ThomasThiebaud