我正在尝试构建一个结合静态和动态元素的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.