2012-06-24 36 views
0

为什么我不能在最后一行使用setContentView(R.layout.main)而没有setContentView(tv)?请向我解释这一点。关于android应用程序“HelloWorld”

package com.mue.helloworld; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.TextView; 

public class HelloWorldActivity extends Activity 

{ 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 

     TextView tv = new TextView(this); 

     tv.setText("Hello, Android i am suvankar"); 

     setContentView(tv); 
    } 

} 
+0

没有得到?您可以在此代码的最后一个函数中设置setContentView(R.layout.main).............是什么问题? –

回答

2

您必须在R.layout.main(一个xml文件)中定义textview,该文件包含活动中对象的信息。 如果您使用的是Eclipse,您可以简单地拖放文本视图,只需打开主文件即可。 (文件夹资源 - >布局 - > main.xml中)

然后哟必须调用它在你的程序:

setContentView(R.layout.main); 
TextView tv = (TextView) findViewById(R.id.tv); //<-- yo have to use the same ID that is in the main.xml file 

,然后你可以设置文本。所有这些都在oncreate函数中。

tv.setText("Hello, Android i am suvankar"); 

那么,我希望我帮了忙。是我的第一个回应

2

您不应该在onCreate中拨打setContentView()两次。请致电setContentView(R.layout.main)或致电setContentView(tv),但不能同时使用两者。我更喜欢两个中的第一个......但是您需要确保TextView在您的布局XML中声明。

0

让我们先尝试了解setContentView()方法的作用。基本上setContentView()将您的用户界面置于您的Activity上。现在为您的活动创建一个UI组件,您可以使用xml资源(例如R.layout.main),也可以在您的代码中获取UI组件的实例并将其动态添加到您的活动中。例如

TextView tv = new TextView(this); 

tv.setText("Hello, Android i am suvankar"); 

setContentView(tv); 

在你的情况,你所创建的TextViewtv的一个实例,设置一些文本,并补充说,你的活动。在这里你不需要使用setContentView(R.layout.main)。但是,如果你在你的布局一个xml布局(main.xml中)文件夹,如下所示:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Hello World" 
    /> 
</LinearLayout> 

,并在您的应用程序,你写setContentView(R.layout.main)的底部,你会看到一个黑色的屏幕与的Hello World写在上面。这是因为您在此创建了一个TextView实例,为其设置了一些文本,但没有通过调用 setContentView(tv)而将它放到您的活动中,而是添加了完全不同的布局资源。如果您使用setContentView(tv)并在您的onCreate()的末尾添加setContentView(R.layout.main),那么您将再次看到Hello World而不是“您好,Android我是suvankar”,因为最终您替换了您的UI资源。但是,如果您忘记添加xml资源并调用'setContentView(R.layout.main)',那么编译器将发出错误消息以找不到指定的xml资源。