android - 如何将布局(由java制作)附加到片段?
问题描述
我想在fragment
不使用任何xml
文件的情况下做例子
我试图layout
只用java制作。之后,我想将其附加到fragment
.
但是必须class
通过使用膨胀override fragment
来返回文件。xml
(这样对吗?)
另外,由于fragment
is 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 文件的情况下制作片段示例
解决方案
无需调用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
方法用于将View
XML 文件中定义的内容加载到内存中。只要您创建了一个LinearLayout
使用上下文的新实例,就不需要膨胀任何东西。
推荐阅读
- wordpress - 创建分层复选框 ACF Wordpress
- javascript - 无效的挂钩调用。钩子只能在函数组件的主体内部调用。在本机反应
- rasa - 无法将 Duckling 部署到 AWS EC2 容器上
- sharepoint - 文档列表项上的按钮以打开“属性窗格”
- c# - .NET WPF 框架 foreach 循环使用复选框
- excel - Excel中的负时间值
- jquery - 如何使用 jquery ajax 在 asp.net 中提交值数据表
- typescript - 使用 MongoDB 对 Express API 的开玩笑测试 - 在本地机器上运行,在 CircleCI 上失败(超过超时)
- reactjs - 如何将集合中的文档数解析为变量?
- reactjs -