首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在android中以编程方式向framelayout添加片段

在android中以编程方式向framelayout添加片段
EN

Stack Overflow用户
提问于 2013-12-08 23:56:56
回答 1查看 70.2K关注 0票数 27

我正在尝试构建一个结合了静态和动态元素的UI。为此,我将我的活动划分为片段-所有的应用程序导航都是通过替换片段来完成的,而不是在活动之间导航。

在我的主活动布局中,我使用了一个FrameLayout

代码语言:javascript
复制
<FrameLayout
        android:id="@+id/mainframe"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:layout_below="@id/topsection"
        android:layout_above="@id/lowersection" />

我有一个这样声明的片段:

代码语言:javascript
复制
public class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragmentlayout, container, false);
    }
}

然后,在我的主活动(扩展FragmentActivity并使用导入的android.support.v4.app.FragmentActivity )中,我尝试将此片段加载到框架布局中。

代码语言:javascript
复制
MyFragment myf = new MyFragment();

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.mainframe, myf);
transaction.commit();

我在许多其他示例中都遵循了这一点,但是我在transaction.add()命令上收到了一个编译器错误,似乎没有人遇到过这个错误。

我收到的错误是:The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, MyFragment)

为什么会这样呢?MyFragment类扩展了Fragment,所以我认为这是可行的。我做错了什么?

编辑:我的主要活动的导入是:

代码语言:javascript
复制
import org.joda.time.DateTime;
import android.app.FragmentTransaction;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-09 00:21:46

检查您的导入。使用android.support.v4.app.FragmentTransaction而不是android.app.FragmentTransaction

此外,请确保您正在使用android.support.v4.app.Fragment并调用getSupportFragmentManager()。很容易错过这个调用/导入。在FragmentManager的提示下,Thx到saiful103a。

票数 31
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20455416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档