SetText with onClick button and onCreate crashes

How do I get the textbox to change when the app starts and how do I get it to change it when I click the button?

MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView myText=(TextView)findViewById(R.id.myActivityTextView);
    myText.setText("Launch Text Change");        
}

public void myButtonclicked(View v){
    TextView myText=(TextView)findViewById(R.id.myActivityTextView);
    myText.setText("Button Change Text");
}

      

activity_main.xml

<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/myText" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Change Text"
    android:id="@+id/myButton"
    android:layout_below="@+id/myText"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:onClick="myButtonclicked"/>

      

+3


source to share


2 answers


TextView

you have an id in your xml myText

. Change your search

TextView myText=(TextView)findViewById(R.id.myActivityTextView); 

      

to



TextView myText=(TextView)findViewById(R.id.myText);

      

and it should work.

+2


source


You are looking for an invalid identifier. Here is the correct way



TextView myText=(TextView)findViewById(R.id.myText);
myText.setText("Launch Text Change");        

      

+1


source







All Articles