按钮动作 - Android应用

时间:2012-04-08 06:57:31

标签: android android-layout

我正在练习Hello,Android ed3这本书。有一个关于创建动作按钮以显示“关于”游戏的示例代码。我已经编辑了所有必要的xml文件。我在以下代码中收到错误。 logcat在第10行显示nullpointer异常:about.Button.setClickListener(this)。请帮助。我也无法理解'this'参数。任何肝脏?

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;
    }

} }

2 个答案:

答案 0 :(得分:1)

看起来你在xml文件中没有“about_button”按钮。您是否为xml中的按钮指定了相同的名称?

答案 1 :(得分: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行...