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”

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

有帮助吗?

解决方案

您尝试将整数作为参数传递给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版本上遇到了一些麻烦。

其他提示

尝试这个:

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

还要确保您的布局XML具有textView txt_1

我试过了 :

Integer.toString(char) and String.valueOf(char)

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

txt.setText(""+char);

从优化的角度来看,这不是很有效的,但是它可以解决问题:)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top