4

我试图部署一个小型 android 应用程序,在其中,我试图向用户显示“Hello World”。

我在这里应用的代码行是(来自互联网资源):

    TextView text = new TextView(this);
    text.setText("Hello World, Here");
    setContentView(text);

我不明白的是:为什么this这里需要关键字?我不能只创建一个普通的香草TextView对象来设置这样的文本:

    TextView text = new TextView();
    text.setText("Hello World, Here");

而且,这里方法的目的是什么setContentView?它像System.out.printlnjava 一样工作吗?有点困惑,任何帮助将不胜感激。谢谢 。

4

5 回答 5

5
 TextView text = new TextView(this);

Why is this key word is required here ?

This refers to the current object which in your case is the Activity as you are probably executing this code from the onCreate of your activity class. And the constructor of TextView class at least requires a context as an argument. And Activity is a subclass to Context so passing "this" does the trick. Thats why you cannot do something like this.

 TextView text = new TextView(); 

Now to answer why we are doing this. Think it in this way. This is a view that needs to attach itself to some context. so that it can also consume many context related privileges in the system.

See context as an individually existing wrapped component of your application that will be binding so many thing in it and has a properly defined life cycle.

Activity is a type of context. Activity is a one visible screen in android application. Actually activity is much more than that. But just to understand this at elementary level.

setContentView says it all itself. The content that activity is going to display in the visible screen it belongs to.

So you declared a TextView and sets it as the content of the activity to be get displayed. Simple.

Hope it helps in understanding it better. You should better follow http://developer.android.com

cheers

于 2013-05-22T11:43:54.693 回答
3
 TextView text = new TextView(this);

this 指的是您的案例活动上下文中的当前上下文,因为您希望在活动中使用文本视图。

public void setContentView(查看视图)

将活动内容设置为显式视图。此视图直接放置在活动的视图层次结构中。它本身可以是一个复杂的视图层次结构。调用此方法时,会忽略指定视图的布局参数。默认情况下,视图的宽度和高度都设置为 MATCH_PARENT。要使用您自己的布局参数,请改为调用 setContentView(android.view.View, android.view.ViewGroup.LayoutParams)。

参数

查看 想要显示的内容。

http://developer.android.com/reference/android/app/Activity.html#setContentView(android.view.View)

在您的情况下, setContentView (text) 您正在将视图(即 textview)设置为活动(即屏幕)。

android 中的 System.out.println("hello") 将在 logcat 中打印 hello。

“this”上下文是什么意思?

于 2013-05-22T11:23:04.477 回答
0

如果它不存在(setContentView() 方法),您将永远不知道在您的活动开始时将执行哪个文件/代码。

您正在使用setContentView()方法设置上下文。

于 2013-05-22T11:33:09.043 回答
0

这是指上下文。setContentview 用于设置布局资源,它以整数作为参数,整数是指布局xml

于 2013-05-22T11:29:19.617 回答
0

文档

视图元素需要将 Context 传递给构造函数,以便它可以访问主题和内容等资源。Activity 是 Context 的子项,因此您可以在此处使用 this。

setContentView 设置用于显示活动的视图元素,您可以传递视图元素或资源 id 的实例。

于 2013-05-22T11:30:31.390 回答