【发布时间】:2021-10-01 05:49:43
【问题描述】:
我正在做课堂练习,告诉我:
- 在名为 ForecastFragment.java 的 Fragment 类中创建一个 TextView,该 Fragment 将显示在 MainActivity.java 中。
- 不要使用xml文件,全部用.java编码
我的工作:
public class ForecastFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_forecast, container, false);
view.setBackgroundColor(Color.BLUE);
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(getActivity());
String text = "Thursday";
textView.setText(text);
linearLayout.addView(textView);
return view;
}
}
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ForecastFragment">
</FrameLayout>
结果:
- TextView 未添加,片段也未添加 => 100% 失败
问题:
- 在 LinearLayout 和 TextView 构造函数中,它们需要 Context 实例,但我们在 Fragment 中,因此“this”关键字 die => 我使用 getActivity() 代替。这是真的还是假的?
- 为什么我的代码不起作用。
- 我仍然不知道如何将 TextView 约束到父级。
- 使用java创建元素比xml难很多,所以需要一些源码来理解
谢谢大家。
【问题讨论】:
-
这是由于您没有将您的 linearLayout 添加到返回的视图中。并且由于它是 View 类的对象,因此您无法添加子尝试使用 ViewGroup,例如 LinearLayout 或其他将 ViewGroup 扩展为父视图而不是视图的视图。
-
你的意思是将片段添加到 ViewGroup 然后将 ViewGroup 添加到 MainActivity。
-
不不,你完全错了,你能分享 fragment_forecast.xml 的代码,以便我更好地解释它。
-
是的,我已经在上面添加了。希望你能帮我解决这个问题。谢谢
标签: java android android-fragments