【问题标题】:Android: fragments: onCreateView isn't calledAndroid:片段:未调用 onCreateView
【发布时间】:2011-08-02 10:27:10
【问题描述】:

我有一个沙盒项目,一切正常,但在实际项目中却没有。 我想我错过了什么......

在我的主要活动中(我已经尽可能地简化了一个项目):

@Override
  public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(createUI());
  }

  public View createUI() {
    LinearLayout rootLayout = new LinearLayout(this);
    rootLayout.setOrientation(LinearLayout.HORIZONTAL);
    rootLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
    LinearLayout leftLayout = new LinearLayout(this);
    leftLayout.setLayoutParams(new LinearLayout.LayoutParams(300, ViewGroup.LayoutParams.FILL_PARENT));
    leftLayout.setId(11111);

    android.widget.TextView textView = new android.widget.TextView(this);
    textView.setText("112233");

    rootLayout.addView(textView);
    rootLayout.addView(leftLayout);
    {
      FragmentTransaction transaction = getFragmentManager().beginTransaction();
      ModelEditorFragment simpleFragment = new SimpleFragment();
      transaction.add(11111, simpleFragment);
    }
    return rootLayout;
  }

在 SimpleFragment.java 中:

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
    TextView textView = new TextView(getActivity());
    textView.setText("SimpleFragmentText");
    return textView;

但是当我开始时,我只看到没有 SimpleFragmentText 的 112233。 在调试时,我注意到从未调用过 onCreateView 方法......为什么?看起来相同的代码在独立应用程序中运行良好...可能还有其他我不知道的事情?

【问题讨论】:

  • 对不起。我只是在实际项目中忘记了 transaction.commit()...

标签: android android-layout android-fragments


【解决方案1】:

我忘记了 transaction.commit:

{
      FragmentTransaction transaction = getFragmentManager().beginTransaction();
      ModelEditorFragment simpleFragment = new SimpleFragment();
      transaction.add(11111, simpleFragment);
      transaction.commit();
    }

【讨论】:

    【解决方案2】:
    rootLayout.addView(textView);
    {
        rootLayout.addView(leftLayout);
        {
          FragmentTransaction transaction = getFragmentManager().beginTransaction();
          ModelEditorFragment simpleFragment = new SimpleFragment();
          transaction.add(11111, simpleFragment);
        }
    }
        return rootLayout;
    

    试试我认为你的 rootLayout 只是缺少 textView 添加部分

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      • 2016-06-13
      相关资源
      最近更新 更多