Android: 添加一个listfragment到交易中

Android: Add a listfragment to the transaction

我尝试用 fragmentTransation.add(...) 添加列表片段,但我做不到,这是一个错误。我想像普通片段一样添加一个列表片段,可以吗?

这是我的 activity 主要代码:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    FragmentList fragmentList = FragmentList.createFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.relativeLayout,fragmentList); //WRONG
    fragmentTransaction.commit();
}

这是我的列表片段 class 代码:

public class FragmentList extends ListFragment
{
public static FragmentList createFragment()
{
    FragmentList fragmentList = new FragmentList();
    return fragmentList;
}

@Override
public void onCreate(Bundle bundle)
{
    super.onCreate(bundle);
    ListView listView = getListView();
    String[] stringa = {"A","B","C"};
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,stringa);
    listView.setAdapter(arrayAdapter);

}

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    super.onCreateView(inflater,container,savedInstanceState);
    View rootView = inflater.inflate(R.layout.fragment, container, false);
    return rootView;
}
}

1) 您不能将 android.app.ListFragmentSupportFragmentManger 一起使用,您可以使用 getFragmentManager()

基本上,检查您的 import 语句。

或者您可以改为扩展 android.support.v4.app.Fragment 并使用 <ListView> 定义您自己的布局(就像您已经在做的那样)

或者您可以使用 android.support.v4.app.ListFragment


不过更重要的是

2) 无法从 onCreate 调用 getListView(),因为还没有视图。

你只需要onCreateView

public class FragmentList extends ListFragment {

    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        super.onCreateView(inflater,container,savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment, container, false);
        String[] stringa = {"A","B","C"};

        ListView listView = (ListView) rootView.findViewById(android.R.id.list);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,stringa);
        listView.setAdapter(arrayAdapter);

        return rootView;
    }
}

此外,

getFragmentManager() // Change accordingly
    .beginTransaction()
    .add(R.id.relativeLayout,new FragmentList())
    .commit();