0

我正在尝试实现一个导航抽屉。“Fragment1”是一个列表片段:

public class Fragment1 extends ListFragment {
private List<String> musicList;

public static ListFragment newInstance(Context context) {
    Fragment1 f = new Fragment1();

    return f;
}

但是我不能使用片段事务来替换主要活动中的片段:

public class MainActivity extends AbstractNavDrawerActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if ( savedInstanceState == null ) {
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new Fragment1()).commit();
    }
}


@Override
protected void onNavItemSelected(int id) {
    switch ((int)id) {
    case 101:
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new Fragment1()).commit();
        break;
    case 102:
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new Fragment2()).commit();
        break;
    }
}

}

replace 方法下面有一条红线,上面写着:

FragmentTransaction 类型中的方法 replace(int, Fragment) 不适用于参数 (int, Fragment1)"

我应该怎么办?

4

1 回答 1

1
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,     new Fragment1()).commit();

IMO,您应该避免在方法代码之后使用方法调用来编写如此长的代码,这很混乱且难以理解!也许尝试:

FragmentTransaction transaction = getActivity().getSupportFragmentManager()
                    .beginTransaction();
Fragment newFragment = new Fragment1();
transaction.add(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
于 2013-08-12T11:34:21.460 回答