我试图使用Fragements。但是在MainActivity.java文件中,transaction.add(R.id.my_layout, testfrag, "");
未正确启动。请在我使用的代码下面找到。
package com.example.testtabs;
import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.TabActivity;
import android.view.Menu;
import android.widget.TabHost;
import android.support.v4.app.Fragment;
import com.example.testtabs.R;
public class MainActivity extends TabActivity {
TabHost tab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragementTest testfrag=new FragementTest();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.my_layout, testfrag, "");//Error is here
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="@+id/my_layout"
>
Error: The method add(int, Fragment, String) in the type FragmentTransaction is not applicable for the arguments (int, FragementTest, String)
Fragement.test
package com.example.testtabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link android.support.v4.app.Fragment} subclass.
*
*/
public class FragementTest extends Fragment {
public FragementTest() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragement, container, false);
}
}
答案 0 :(得分:19)
变化:
import android.app.FragmentManager;
import android.app.FragmentTransaction;
为:
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
或---
变化:
import android.support.v4.app.Fragment;
到
import android.app.Fragment;
答案 1 :(得分:2)
所有片段应该是android.app.Fragment。如果你想使用android.support.v4.app.Fragment,你应该使用etSupportFragmentManager()来获取管理器。
答案 2 :(得分:1)
它为我工作:
使用getSupportFragmentManager();
而不是使用getFragmentManager