【发布时间】:2015-02-05 12:49:16
【问题描述】:
在this guide 之后,我正在尝试设置片段,但这里出现错误:
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, myfrag).commit();
无法解析方法 add(int, com.mypackage.MyFragment)
我有一个带有 fragment_container id 和 MyFragment 扩展片段的 FrameLayout...所以我不确定我在这里做错了什么...第一次使用片段...
这是我的代码
主要活动:
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();
...
我的片段:
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" />
【问题讨论】:
-
您是否导入了正确的 Fragment-class ?
-
您可能需要像这样添加额外的标签参数:getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, myfrag,"tag_name").commit();