我只是按照教程进行操作,但不明白为什么它显示错误。这是我的代码..
FragmentManager fManager;
@Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_test);
fManager = getFragmentManager();
MakeTransaction();
}
public void MakeTransaction(){
MyFragmentClass mfrag = new MyFragmentClass();
FragmentTransaction trans = fManager.beginTransaction();
trans.add(R.id.view_group,mfrag,"G");
}
在“trans.add(R.id.view_group,mfrag,"G");”行上我收到错误...
错误是fragment事务中的add()无法应用..
这是 fragment 类代码##
public class MyFragmentClass extends Fragment {
Button ph;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_setup, container,false);
}
这是主要的 xml 代码,其中有两个 fragment ..
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/view_group"
android:orientation="horizontal">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment_setup"
/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment_display"
/>
</LinearLayout>
</LinearLayout>
最佳答案
The error is add() in fragment transaction cannot be applied ..
这通常是因为 Fragment
子类的 Fragment 导入与 Activity
中的 Fragment 导入不匹配。在您的情况下,您使用的是 getFragmentManager,而 MyFragmentClass 可能是支持库中 Fragment 的子类。在您的 Activity
中使用 getSupportFragmentManager()
而不是 getFragmentManager()
。为此,您必须在 FragmentActivity
、AppCompatActivity
或 ActionBarActivity
之间扩展一个
关于java - 如何成功添加fragment?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30543809/