TextView is null

十年热恋 提交于 2019-12-20 06:15:47

问题


I'm having a problem with TextView. After pressing a button I want to append something to that TextView but apparently is null all the time.

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

I want to append some text to the reply TextView but apparently, it returns NullPointerException all the time. I am lost, I don't know what is failing.


回答1:


Not use v.findViewById, but this.findViewById




回答2:


TextView is null

Declare your TextView variable as global and intialize it in the onCreate()

Try this code

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


    }


来源:https://stackoverflow.com/questions/42735577/textview-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!