我正在尝试构建一个结合了静态和动态元素的UI。为此,我将我的活动划分为片段-所有的应用程序导航都是通过替换片段来完成的,而不是在活动之间导航。
在我的主活动布局中,我使用了一个FrameLayout
<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" />
我有一个这样声明的片段:
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;
发布于 2013-12-09 00:21:46
检查您的导入。使用android.support.v4.app.FragmentTransaction
而不是android.app.FragmentTransaction
。
此外,请确保您正在使用android.support.v4.app.Fragment
并调用getSupportFragmentManager()
。很容易错过这个调用/导入。在FragmentManager的提示下,Thx到saiful103a。
https://stackoverflow.com/questions/20455416
复制相似问题