2015-11-07 195 views
0

尽管看起来像是一个简单的问题,但我无法使其工作。 (在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找到我的文本?

+0

的TextView =会将myText(的TextView)findViewById(R.id.worldMood);在onCreate和android中执行该操作:name to android:id –

回答

3

你必须使用android:id指定属性不android:name的ID。所以改变下面的行,

android:name="@+id/worldMood" 

android:id="@+id/worldMood" 
+1

完美答案!!!!! +1上 –

+1

似乎它会工作的确如此,在我试试的路上。只能在8分钟内接受答案,我会的。谢谢hawkeye! ;) – Fundhor

-1

试试这个。

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

坦克你试图帮忙;)不是解决方案,但我很感激。 – Fundhor