文本视图为空

TextView is null

我在使用 TextView 时遇到问题。按下按钮后,我想向该 TextView 添加一些内容,但显然一直都是 null。

fragment_one.xml

....
<TextView
    android:id="@+id/reply"
    android:layout_below="@+id/test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/reply"/>
<Button android:text="@string/_0"
        android:id="@+id/_0"
        android:onClick="handleButtons"/>
....

ActivityTwo.java

....
public void handleButtons(View v){
    setContentView(R.layout.fragment_one);
    TextView tv = (TextView) v.findViewById(R.id.reply);
    if(v.getId() == R.id._0){
        tv.append("hi");
    }
....

我想将一些文本附加到 reply TextView,但显然,它总是 returns NullPointerException。我迷路了,我不知道失败了什么。

TextView is null

将您的 TextView 变量声明为全局变量并在 onCreate() 中初始化它

试试这个代码

    public class MainActivity extends AppCompatActivity{
   TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    tv = (TextView)findViewById(R.id.reply);

    }
    public void handleButtons(View v){

        if(v.getId() == R.id._0){
            tv.append("hi");
        }


    }

不使用 v.findViewById,但 this.findViewById