【发布时间】:2013-12-25 15:57:09
【问题描述】:
我正在尝试构建一个结合了静态和动态元素的 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;
【问题讨论】:
-
您是否在主活动类中扩展 FragmentActivity?
-
有时我们在执行键盘快捷键时从两个不同的位置导入两个相同的类时会出错,我建议您交叉检查导入的类,因为您没有像我之前认为的那样使用支持库。不过,如果您可以将导入的类放在这里,对我们找出问题会有帮助。
-
@wyoskibum 我的主要活动确实扩展了
FragmentActivity,而不是Activity。 -
@saiful103a 我正在使用导入
android.support.v4.app.FragmentActivity。这是 eclipse 提示我导入的唯一选项 - 我应该使用其他选项吗? -
从支持库android.support.v4.app.FragmentTransaction中导入FragmentTransaction;也因为您使用支持库使用 getSupportFragmentManager() 而不是 getFragmentManager()
标签: android fragment android-framelayout