关注this guide我正在尝试设置片段,但我在这里遇到错误:
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, myfrag).commit();
无法解析方法add(int,com.mypackage.MyFragment)
我有一个带有fragment_container id的FrameLayout和MyFragment扩展片段...所以我不确定我在这里做错了什么...第一次使用片段......
这是我的代码
主要活动:
public class MainFragmentActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_fragmentactivity);
int frag = getIntent().getExtras().getInt("fragment");
if(findViewById(R.id.fragment_container) != null) {
if(savedInstanceState != null) return;
MyFragment myfrag= new MyFragment();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, myfrag).commit();
...
MyFragment:
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.settings_devicelist, container, false);
}
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
listView = (ListView)getView().findViewById(R.id.lvHosts);
...
settings_framentactivity.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
答案 0 :(得分:2)
确保您导入的是android.support.v4.app.Fragment
课程,而不是android.app.Fragment
答案 1 :(得分:0)
不确定我的问题中的代码是否是一个错误,但是写出来的一切都很好。
MyFragment frag = new MyFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, frag);
transaction.addToBackStack(null);
transaction.commit();