【问题标题】:How to attach layout(made by java) to fragment? [closed]如何将布局(由java制作)附加到片段? [关闭]
【发布时间】:2019-04-15 04:46:30
【问题描述】:

我想在不使用任何xml 文件的情况下制作fragment 示例

我尝试仅使用 java 制作 layout。 之后,我想把它附加到fragment

但是override fragment 中的class 必须使用inflate 返回xml 文件。 (对吗?)

另外,由于fragment 不是Activity,我不能在上面使用setContentView

我该如何解决这个问题?

public class FragmentA extends Fragment {

public FragmentA() {

}

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

    LinearLayout linear = new LinearLayout(getContext());
    linear.setOrientation(LinearLayout.VERTICAL);
    linear.setBackgroundColor(Color.WHITE);

    TextView tv = new TextView(getContext());
    tv.setText("Hello World1");
    linear.addView(tv);


    return inflater.inflate((XmlPullParser) linear, null);
}
}

我想在不使用任何 xml 文件的情况下制作片段示例

【问题讨论】:

  • 更改为return linear;。就是这样。
  • linear是View实例不需要使用inflate方法,只需从onCreateView 返回linear实例
  • 我想得太远了...谢谢!

标签: android android-layout android-activity fragment


【解决方案1】:

无需调用inflate method,只需返回linear变量即可。

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

    LinearLayout linear = new LinearLayout(getContext());
    linear.setOrientation(LinearLayout.VERTICAL);
    linear.setBackgroundColor(Color.WHITE);

    TextView tv = new TextView(getContext());
    tv.setText("Hello World1");
    linear.addView(tv);


    return linear;
}

inflate 方法用于将 XML 文件中定义的 View 加载到内存中。只要您使用上下文创建了LinearLayout 的新实例,就不需要膨胀任何东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 2015-04-27
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多