通过 java 代码(没有 .xml)在 Fragment class 中创建 android TextView

Create android TextView inside Fragment class by java code (without .xml)

我正在做 class 练习,这些练习告诉我:

我的作品:

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>

结果:

问题:

谢谢大家

发生以下事情是因为您没有将 LinearLayout 对象添加到任何将在屏幕上呈现的父对象。截至目前,它是无法添加子视图的视图 class 的视图对象。

因此进行以下更改:

public class ForecastFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        FrameLayout view = (FrameLayout) inflater.inflate(R.layout.fragment_forecast, container, false);
        view.setBackgroundColor(Color.BLUE);

        LinearLayout linearLayout = new LinearLayout(view.getContext());
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        TextView textView = new TextView(view.getContext());
        String text = "Thursday";
        textView.setText(text);

        view.addView(linearLayout);    
        linearLayout.addView(textView);
        return view;
    }
}

现在我将回答您的一些问题: 问题:

  • 在 LinearLayout 和 TextView 构造函数中,它们需要 Context 实例,但我们在 Fragment 中,所以“this”关键字死了 => 我使用 getActivity() 代替。这是真的还是假的?

it can work but if you try to use getActivity() while fragment is detached from activity it will return null so you have to check every time about that. so instead you can use viewObject.getContext() so it will be not null.

  • 为什么我的代码不起作用。

as i explained earlier it;s working but you can't see it cause it not being attached to layout which is currently being shown.

  • 我仍然不知道如何将 TextView 限制为父级。使用java&创建元素比xml难多了,所以我需要一些源代码来理解

for this you have to practice about each ViewGroup and how they manage child views. and also you can find many references online about them.