TextView为null

时间:2017-03-11 13:09:25

标签: java android getview

我遇到TextView问题。按下按钮后,我想向TextView追加一些内容,但显然一直都是null。

fragment_one.xml

<h1>London</h1>
<h3>London is the capital city of England.</h3>
<p>It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p>

ActivityTwo.java

....
<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"/>
....

我想将一些文本附加到.... 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"); } .... TextView,但显然,它一直返回NullPointerException。我迷路了,我不知道什么是失败的。

2 个答案:

答案 0 :(得分:1)

不使用v.findViewById,而是使用this.findViewById

答案 1 :(得分:0)

  

TextView为空

将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");
        }


    }