android setContentView无法正常工作

时间:2012-01-21 16:15:06

标签: java android

不重复:我的问题比其他所有问题都简单。

我一直在尝试关注android hello world tutorial,我无法得到第一个工作示例。

这是我的代码:

package com.example.helloandroid;

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

public class HelloAndroid 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");
        setContentView(tv);
    }
}

如您所见,我直接从教程中复制并粘贴。 问题是,它不是显示Hello,Android,而是显示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, HelloAndroid"
    />
</LinearLayout>

请注意,这是在我启动项目时自动创建的,我没有把它放在那里。

4 个答案:

答案 0 :(得分:1)

为什么你有两个文本相同的TextView?你不应该这样做,如果你只打算使用一个,那么只使用一个。

您的XML很好,但您的活动代码需要更改:

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

这是对你正在做什么的解释......

您正在动态构建TextView并将ContentView设置为TextView很好,但这不是您的初衷。您的初衷或样本的初衷是使用布局文件,然后将该活动的内容视图设置为该布局文件,而不仅仅是该文本视图。

<强>更新

代替OP所说的,他确实想要动态构建一个TextView实例并将其应用到屏幕上。如果是这种情况,那么你必须......:

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT));
        tv.setText("Hello, Android");
        setContentView(tv);
    }
}

唯一的区别是TextView具有定义它在屏幕上显示方式的属性。您可以使用FILL_PARENT或WRAP_CONTENT。

答案 1 :(得分:1)

您尚未在应用程序中设置xml文件或布局。您正在直接调用该视图。您需要在布局下调用您的视图。

语法:setContentView(R.layout.your xml文件名);

答案 2 :(得分:0)

试试这个:你最后不需要做setContentView。如果你这样做,它将覆盖你在xml中的内容。

  @Override     
public void onCreate(Bundle savedInstanceState) {  
       super.onCreate(savedInstanceState);    
       setContentView(R.layout.yourxmlfile);     
       TextView tv = (TextView)findViewById(R.id.helloText);
       tv.setText("Hello, Android");  
      } 




 <TextView   android:id="@+id/helloText"    android:layout_width="fill_parent"    
   android:layout_height="wrap_content"
       android:text="Hello World, HelloAndroid"       />

答案 3 :(得分:0)

关于logcat的问题,您可以在Eclipse的Debug透视图中找到它。它是来自系统和用户代码的错误消息的日志。