首页 > 解决方案 > 如何将布局(由java制作)附加到片段?

问题描述

我想在fragment不使用任何xml文件的情况下做例子

我试图layout只用java制作。之后,我想将其附加到fragment.

但是必须class通过使用膨胀override fragment来返回文件。xml(这样对吗?)

另外,由于fragmentis not a 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 文件的情况下制作片段示例

标签: androidandroid-layoutandroid-activityfragment

解决方案


无需调用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方法用于将ViewXML 文件中定义的内容加载到内存中。只要您创建了一个LinearLayout使用上下文的新实例,就不需要膨胀任何东西。


推荐阅读