2012-04-08 67 views
0

我正在练习本书Hello,Android ed3.There有一个示例代码,用于创建一个动作按钮以显示'关于'游戏。我编辑了所有必需的xml文件。我收到错误在下面的代码中.logcat显示第10行的空指针异常:about.Button.setClickListener(this)。请帮助。另外我一直无法理解'this'参数。任何hep?按钮动作-Android应用程序

public class Sudoku extends Activity implements OnClickListener { 
private static final String TAG = "Sudoku"; 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     // Set up click listeners for all the button 
     View aboutButton = findViewById(R.id.about_button); 
     aboutButton.setOnClickListener(this); 

    } 

    public void onClick(View v) { 
      switch (v.getId()) { 
      case R.id.about_button: 
      Intent i = new Intent(this, About.class); 
      startActivity(i); 
      break; 
    } 

}}

回答

1

看起来你没有 “about_button” 在xml文件按钮。你在xml中为按钮命名了吗?

+0

确保您的main.xml是一个与它或更改按钮它到正在使用的实际布局文件。 – L7ColWinters 2012-04-08 07:05:40

+0

做完了所有的代码仍然不会运行! – Maxsteel 2012-04-08 08:23:54

+0

在这里发布您的XML文件..你仍然得到相同的错误? – San 2012-04-08 08:27:44

0
public class Sudoku extends Activity implements OnClickListener { 
private static final String TAG = "Sudoku"; 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    // Set up click listeners for all the button 
    Button aboutButton = (Button) findViewById(R.id.about_button); 
    aboutButton.setOnClickListener(this); 

}

public void onClick(View v) { 
     if(v == aboutButton){ 
     Intent i = new Intent(this, About.class); 
     startActivity(i); 
     break; 
} 

试试这个...只是改变2-3行...

+0

按原样复制了代码。仍然显示相同的错误。请在此解释'this'参数是什么? – Maxsteel 2012-04-08 08:24:21

+0

谢谢everyone.It工作! :) – Maxsteel 2012-04-08 08:30:53

相关问题