android - findViewById 在调用 setContentView 后返回 null

标签 android textview findviewbyid

我尝试通过 findViewById(int) 在我的 java 文件中引用一个 TextView,但即使在使用正确的布局文件调用 setContentView(int) 之后,这似乎也返回 null。

Help.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/tvBoxHelp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/help"
    android:layout_gravity="center"
    android:textSize="20sp" />

</LinearLayout>

Help.java

 public class Help extends Activity {

private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    setContentView(R.layout.help);
    tv = (TextView) findViewById(R.id.tvBoxHelp);
    tv.setText("text");
    super.onCreate(savedInstanceState);
    }
  }

提前致谢。

最佳答案

您的 super.onCreate(savedInstanceState); 位置导致了问题。

用这个替换你的 Help.java

public class Help extends Activity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.help);

        tv = (TextView) findViewById(R.id.tvBoxHelp);
        tv.setText("text");

    }
}

关于android - findViewById 在调用 setContentView 后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14028648/

相关文章:

android - 仅 Lollipop 崩溃 "Failed resolution of: Landroid/support/v7/appcompat/R$styleable"

android - 父 View 没有得到长按事件

android - 如何在形状xml中的笔画两侧制作圆角

android - Tablayout 文本颜色没有变化,android?

android - 如何在自定义 TextView 中获取命名空间为 "android"的属性

java - @override 在 android 中使用 onDraw 导致错误

android - TextView添加drawable的不同方式

java - 将 "findViewById"用于 map View 时出错

android - FindViewById 其中 ID 是动态字符串

android - 空指针异常 - findViewById()