Reputation: 3577
Although it seems like easy question I can't make it work. (There are similar questions on StackOverFlow but doesn't seem to work for me, using xml onClick attribute).
I want to change a text when a button is clicked (basics...)
I'm using the following code.
package com.example.mathieu.pangolin;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doSomething(View v) {
TextView myText = (TextView) this.findViewById(R.id.worldMood);
myText.setText("The word is happy");
}
}
and the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:name="@+id/worldMood"
android:text="Grumpy World!"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button android:name="@+id/worldButton"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="doSomething"
android:text="Make the World Happy" />
</RelativeLayout>
I'm getting an error message, but can't figure out the solution. Kind of a NullPointerException on myText ? What is wrong that I can't find my text by its Id?
Upvotes: 0
Views: 228
Reputation: 132982
You have to use android:id
to specify id of an attribute not android:name
. So change the following line,
android:name="@+id/worldMood"
to
android:id="@+id/worldMood"
Upvotes: 3
Reputation: 979
try this.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myText = (TextView)findViewById(R.id.worldMood);
}
public void doSomething(View v) {
myText.setText("The word is happy");
}
}
Upvotes: -1