textView.setText(); 崩溃

3
我的应用中setText()方法返回null,为什么?
public class GetValue extends Activity {
    char letter = 'g';
    int ascii = letter;

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

        TextView textView = (TextView)findViewById(R.id.txt_1);
            textView.setText(ascii);
    }
}

无论我放入什么文本,它都会崩溃。为什么setText()总是返回null?

提前感谢。

解决方案:我的错误在xml文件中。我写成了: android:text="@+id/txt_1" 而应该是: android:id="@+id/txt_1"

非常感谢所有答案和评论!


你确定textView还没有为空吗?能否提供一个错误信息? - janoliver
可能是 findViewById() 没有起作用。你确定你定义了一个名为 txt_1 的 TextView 吗? - RoflcoptrException
请发布您的main.xml文件。 - Marcos Vasconcelos
3个回答

9

您试图将整数作为参数传递给setText方法,但它会将其视为资源ID。如果要显示计算出的文本,请将其作为字符串传递:textView.setText("g");

编辑:请检查您的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:id="@+id/txt_1"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="myTextView"/>
</LinearLayout>

也许您可以尝试清理项目(在Eclipse中选择项目->清理),我最近在最新的ADT版本上遇到了一些关于R文件生成的问题。

我已经尝试过使用普通文本。我唯一知道的就是setText()这行代码会导致程序崩溃。我知道我的xml文件没有问题。logcat显示textView变量返回null。我认为我使用了setText()方法有误。 - user662005

5

试试这个:

textView.setText(Integer.toString(ascii)); 

也请确保您的布局xml文件中有TextView txt_1。

2
我已经尝试过:
Integer.toString(char) and String.valueOf(char)

两者都没有起作用。 唯一的解决方案是:

txt.setText(""+char);

这种方法在优化方面并不是很高效,但它确实能起到作用 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接