问题
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