我正在尝试构建一个既包含静态元素又包含动态元素的UI.为此,我将活动分为多个片段-然后,所有应用程序的导航都是通过替换片段而不是在活动之间进行导航来完成的.
I am trying to build a UI combining both static and dynamic elements. For this, I have divided my activity into fragments - all app navigation is then done by replacing fragments instead of navigating between activities.
在我的主要活动布局中,我使用的是FrameLayout:
In my main activity layout, I am using a 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" />我有一个这样声明的片段:
I have a fragment declared as such:
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)中,我试图将此片段加载到框架布局中.
Then, in my main activity (which extends FragmentActivity and uses the import android.support.v4.app.FragmentActivity, I am attempting to load this fragment into the frame layout.
MyFragment myf = new MyFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.add(R.id.mainframe, myf); transactionmit();我在许多其他示例中都遵循了此规则,但是我在transaction.add()命令上收到了一个编译器错误,似乎没有其他人遇到过该错误.
I have followed this from many other examples, however I am receiving a compiler error on the transaction.add() command, which nobody else seems to have encountered.
我收到的错误是:The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, MyFragment).
这是为什么? MyFragment类扩展了Fragment,所以我认为这会起作用.我在做什么错了?
Why is this? The MyFragment class extends Fragment so I would've thought this would work. What am I doing wrong?
我主要活动的进口是:
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;推荐答案
检查您的导入.使用android.support.v4.app.FragmentTransaction代替android.app.FragmentTransaction.
Check your imports. Use android.support.v4.app.FragmentTransaction instead of android.app.FragmentTransaction.
此外,请确保您正在使用android.support.v4.app.Fragment并调用getSupportFragmentManager().很容易错过此调用/导入.在FragmentManager的提示下,对saiful103a表示感谢.
Furthermore be sure you are using android.support.v4.app.Fragment and calling getSupportFragmentManager(). It's easy to miss this calls / imports. Thx to saiful103a with the hint of the FragmentManager.
更多推荐
以编程方式向Android中的framelayout添加片段
发布评论