我看到有关于这个主题的几个问题,但我仍然无法理解。 Android documentation声明您可以添加这样的片段:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); ExampleFragment fragment = new ExampleFragment(); fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.commit();
但是当我尝试使用我的代码时,它却找不到.add()
方法......
MainActivity
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment frag = new MyFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.myContainer, frag);
fragmentTransaction.commit();
}
}
MyFragment
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class MyFragment extends Fragment {
public MyFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_fragment, container, false);
return rootView;
}
}
activity_main
<FrameLayout 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:id="@+id/myContainer"
tools:context="com.example.alin.lynda_fragments008.MainActivity">
</FrameLayout>
my_fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context="com.example.alin.lynda_fragments008.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello from a fragment" />
</LinearLayout>
答案 0 :(得分:2)
将getFragmentManager()
更改为getSupportFragmentManager()
;
答案 1 :(得分:-1)
您不必使用SupportFragmentManager。你很可能还有其他一些问题。方法add可根据文档提供。 https://developer.android.com/reference/android/app/FragmentTransaction.html#add(int,%20android.app.Fragment)
您使用的是Android Studio吗? 键入fragmentTransaction后,您应该能够看到方法的建议。(OSX上的cmd +空格)