android - 为什么 findViewById() 抛出空异常?

标签 android findviewbyid

为什么 findViewById 抛出 NULL 异常?这是布局和源代码文件:

<RelativeLayout 
...
tools:context=".MainActivity" >

<TextView 
    android:id="@+id/usernameText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</RelativeLayout>

这是 MainActivity 中的源代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);      
    try{
        TextView text=(TextView)MainActivity.this.findViewById(R.id.usernameText);
        text.setText(10);
    }catch(Exception e){
        Log.i("Log", e.getMessage()+"Error!"); // LogCat message

    }

}

但是,findViewById() 返回 null,我什至不知道为什么。这段代码非常简单。

最佳答案

text.setText(10);

通过这种方式,您正在寻找 id = 10 的 String 您应该更改

 text.setText(String.valueOf(10));

关于android - 为什么 findViewById() 抛出空异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16542473/

相关文章:

android - Imageview 变得模糊

Android:WebView 在中心加载图像

android - 不需要转换 findViewById 的结果?

android - findViewById 返回 null - Android - setContentView

java - Android:对 findViewById 的引用

android - 为什么单击网页内容中的选择标签会导致崩溃?

java - 当我滚动 ListView 时, TextView 的默认值是 0

android - Kotlin : safe lambdas (no memory leak)?

android - 无法获取自定义操作栏中项目的引用

android - 空指针异常 - findViewById()