试图从活动中填写片段列表

时间:2014-02-28 08:45:00

标签: java android

我正在尝试从活动填充 ListFagment 。结果我收到Content view not yet created错误。我在这里找到了一些答案,我尝试使用onActivityCreated(),但它没有帮助。请帮我调试问题。

我的活动课

public class MainActivity extends Activity{
    FragmentTransaction ft;
    fragment1 frag1;
    FrameLayout container;

    String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
        "Blackberry" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frag1 = new fragment1();
        FragmentManager fm = getFragmentManager();
        fm.beginTransaction()
        .add(R.id.container, frag1)
        .commit();
        ListView list = frag1.getListView();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, values);
        list.setAdapter(adapter);
    }
}

我的片段类

public class fragment1 extends ListFragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.frag1, null);
        return view;
    }
}

我的日志堆栈跟踪。此行返回错误ListView list = frag1.getListView();

`E/AndroidRuntime(431): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fragmentlisttest/com.example.fragmentlisttest.MainActivity}: java.lang.IllegalStateException: Content view not yet created`

谢谢

2 个答案:

答案 0 :(得分:0)

ListView list = getListView();

应该在片段中的onActivityCreated而不是

ListView list = frag1.getListView();
MainActivity中的

。您需要等到片段附加到活动

onActivityCreated中的ListFragment

ListView list = getListView();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1, values);
 list.setAdapter(adapter);

同时移动下面的

String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
    "Blackberry" }; 
ListFragment之前onCreateView中的

答案 1 :(得分:0)

尚未创建活动的问题您必须在OnActivityCreated中运行代码而不是OnCreate