以编程方式将片段添加到android中的framelayout

 Jessica 发布于 2023-02-12 10:55

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

在我的主要活动布局中,我使用的是FrameLayout:


我有一个片段声明如下:

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,我试图将此片段加载到框架布局中.

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,所以我会一直认为这是可行的.我究竟做错了什么?

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

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;

Steve Benett.. 31

检查你的进口.用android.support.v4.app.FragmentTransaction而不是android.app.FragmentTransaction.

此外,请确保您正在使用android.support.v4.app.Fragment和呼叫getSupportFragmentManager().很容易错过这个电话/进口.使用FragmentManager的提示,转到saiful103a.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有