使用Android模板创建的tabbed activity项目之问题(can’t convert taba to fragment)

本文解决了使用Android TabbedActivity模板创建项目时遇到的问题,即无法将taba转换为Fragment。通过修改getItem方法并创建对应的Fragment类及布局XML,成功实现了Tab切换功能,并指出了Fragment导入路径不一致导致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文首发在我的主力博客:http://anforen.com/wp/2015/11/android-template-created-the-problem-of-using-tabbed-activity-project-can-not-convert-taba-to-fragment/

创建新的android项目时,使用tabbed activity模板,自动配置好viewpager等。


@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).


return PlaceholderFragment.newInstance(position + 1);
}
改为:


@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).


switch (position) {
case 0:
return new taba();



case 1:
return new tabb();

case 2:
return new tabc();

default:
// this page does not exists
return null;
}
// return PlaceholderFragment.newInstance(position + 1);
}


并去新建3个taba.java tabb.java tabc.java,像这样
 
public class taba extends Fragment{



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {




    View rootView = inflater.inflate(R.layout.fragment_a, container,
            false);
    return rootView;
}


}


以及对应的layout xml,像这样
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.samepledemo.taba" >


    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="taba" />


</RelativeLayout>


以上,其实在网上有很多,特别是stackoverflow上。
其实我写这个,主要是因为在接下来遇到怪问题了,正准备打开android studio来对比一下。
结果找到原因。
在getitem方法这个java文件中,使用的是import android.support.v4.app.Fragment;
而在taba.java中使用的是
import android.app.Fragment;
所以,最后全改为
import android.support.v4.app.Fragment;
就行了。


import android.support.v4.app.Fragment;和import android.app.Fragment;主要区别就是:

android.support.v4.app.Fragment支持最低到1.6的andorid版本,android.app.Fragment支持最低到3.0

原文首发在我的主力博客:http://anforen.com/wp/2015/11/android-template-created-the-problem-of-using-tabbed-activity-project-can-not-convert-taba-to-fragment/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值