ボタンの配列を作成しようとしていて、onClickイベントをすべて作成しようとしています。これは私のコードです。 .MyTest.testing)が予期せず停止しました。もう一度やり直してください)何がどこにあるのか不明です。私は基本的な何かを欠いている必要があります、私はアプリを作成しようとしていない、私はちょうどAndroid、特にJavaを傾けています。ボタンの配列を作成して、すべてのoneClickイベントを作成する
は、ここでは、とNullReferenceExceptionを取得しているように見えます私のコード
package com.MyTest.testing;
import static android.widget.Toast.makeText;
import java.util.Random;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class TreActivity extends Activity {
/** Called when the activity is first created. */
//declaring some public int vars
int isPressed1 = 1;
int isPressed2 = 1;
int isPressed3 = 1;
int isPressed4 = 1;
int isPressed5 = 1;
int isPressed6 = 1;
int isPressed7 = 1;
int isPressed8 = 1;
int isPressed9 = 1;
int isPressed10 = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMethod();
}; //End of onCreate (Bundle savedInstanceState)
public void myMethod() {
MyClickHandler handler = new MyClickHandler();
Button[] buttons = fnButtonArray();
for (Button button : buttons) {
button.setOnClickListener(handler);
}
}
class MyClickHandler implements View.OnClickListener {
public void onClick(View v) {
Toast.makeText(TreActivity.this, ((Button) v).getText() , Toast.LENGTH_SHORT).show();
}
}
public Button[] fnButtonArray(){
Button arrButtons[] = new Button[11];
// started with 1 not 0 for the array to match the button numbers
arrButtons[1] = (Button) findViewById(R.id.btn1);
arrButtons[2] = (Button) findViewById(R.id.btn2);
arrButtons[3] = (Button) findViewById(R.id.btn3);
arrButtons[4] = (Button) findViewById(R.id.btn4);
arrButtons[5] = (Button) findViewById(R.id.btn5);
arrButtons[6] = (Button) findViewById(R.id.btn6);
arrButtons[7] = (Button) findViewById(R.id.btn7);
arrButtons[8] = (Button) findViewById(R.id.btn8);
arrButtons[9] = (Button) findViewById(R.id.btn9);
arrButtons[10]= (Button) findViewById(R.id.btn10);
return arrButtons;
}
} //public class TreActivity extends Activity
なぜ26個の要素の配列をインスタンス化し、次に10個だけを埋めますか?配列は0から始まり、1から始まらない0から始まります。 – methodin
26から11までの数を修正しました。ボタンの数と一致するようにゼロではなく1から始めました。だから0は何もない。 –
しかし、反復子は要素が0であると期待しています。したがって、0番目の要素がnullであるためsetOnClickListenerをnullにしようとしています。 – methodin