代码段展示了在 Activity 中获取上下文并使用它来创建和操作 TextView 对象,最后将其添加到布局中。
首先,通过将当前的 Activity 实例赋值给 context 变量,获取了当前的上下文。
接下来,使用 context 创建了一个 TextView 对象,并设置了其文本内容为 “Hello, Android!”。
最后,通过 findViewById 方法获取到布局中的 LinearLayout 对象,并使用 layout.addView(textView) 将 TextView 添加到布局中。
这样,最终在用户界面中就会显示一个包含 “Hello, Android!” 文本内容的 TextView。
// 在 Activity 中获取 Context
Context context = this;
// 创建一个 TextView 对象,并设置文本内容
TextView textView = new TextView(context);
textView.setText("Hello, Android!");
// 在布局中添加 TextView
LinearLayout layout = findViewById(R.id.layout_main);
layout.addView(textView);