【问题标题】:Android - why is this telling me "Content view not yet created"?Android - 为什么这告诉我“尚未创建内容视图”?
【发布时间】:2012-02-15 00:42:56
【问题描述】:

这是在数据库片段上填充列表视图:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {

            LinearLayout Layout5 = (LinearLayout) inflater.inflate(R.layout.tab_frag5_layout, container, false);

            Cursor allBands;
            MyDatabase db;

            Context ctx = (Context)TabFragment5.this.getActivity();


            db = new MyDatabase(ctx);
            allBands = db.getBands();


            ListAdapter adapter = new SimpleCursorAdapter (ctx, 
                    R.layout.listelement, 
                    allBands, 
                    new String[] {"BandName"},  
                    new int[] {R.id.text15});

            getListView().setAdapter(adapter);  

            return Layout5;

         }

为什么这会在 logcat 上给我“尚未创建内容视图”?片段打开时程序强制关闭...

【问题讨论】:

  • 不应该是第一个语句 setContentView(..)?
  • 我不这么认为,我正在处理片段。

标签: android android-listview


【解决方案1】:

我通过将适配器和 getListview 移动到 onActivityCreated(...) 来解决它。

onCreateView 只是膨胀并返回布局。

【讨论】:

  • 当您调用 setAdapter() 时,ListFragment 会检查以确保您的布局中定义了一个列表,并且由于 onCreateView() 没有为片段提供其视图,因此这是一个先有鸡还是先有蛋的问题。
  • setAdapter() 和 getListView() 都进行确保检查吗?我确定 getListView(),但不确定 setAdapter()
  • 为什么不用 onViewCreated。这似乎是最直观的选择。
【解决方案2】:

Fragment 通常应该放在Activity 中,而onCreateView() 会将Fragment 的布局贡献给它的容器Activity

引自http://developer.android.com/guide/topics/fundamentals/fragments.html

片段通常用作活动用户界面的一部分,并且 为活动贡献自己的布局。

因此,问题可能是由于您的容器Activity 中缺少setContentView() 而不是您的Fragment 引起的。

【讨论】:

【解决方案3】:

我遇到了同样的问题,但我的错是通过接口从后台任务调用(不可见的)片段。所以不可见的片段试图使用它不可用的视图......我用相同的解决方案修复它:接口函数检查片段是否为isVisible()。 谢谢你告诉我正确的方向......

 public void updateListInterface(){
    if(this.isVisible()) {
        this.initListAdapter();
        getLoaderManager().restartLoader(0, null, this);
    } else {
        Log.v(TAG, "view is not visible");
    }
}

【讨论】:

    猜你喜欢
    • 2016-09-07
    • 2014-04-13
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    相关资源
    最近更新 更多