使用列表片段进行片段事务

时间:2013-08-12 11:25:57

标签: java android fragment android-listfragment

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

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

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

    return f;
}

但是我无法使用fragmenttransaction替换主要活动中的片段:

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;
    }
}

}

替换方法下面有一个红线,并说:

  

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

我该怎么办?

1 个答案:

答案 0 :(得分: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();