尽管看起来像是一个简单的问题,但我无法使其工作。 (在StackOverFlow上有类似的问题,但似乎不适用于我,使用xml onClick属性)。Android,onClick按钮
我想
我使用下面的代码更改文本时,一个按键(基础知识...)。
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");
}
}
和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>
我收到一条错误信息,但无法找出解决方案。在myText上有一种NullPointerException? 什么是错的,我无法通过它的Id找到我的文本?
的TextView =会将myText(的TextView)findViewById(R.id.worldMood);在onCreate和android中执行该操作:name to android:id –