我正在制作一个Sudoku应用程序,我想添加一个移动计数器,所以我有一个textView,每次用户输入一个数字时都会显示movecount
public class NumberButton extends Button implements OnClickListener {
private int number;
TextView moveCountText;
private int moves;
private String message;
public NumberButton(Context context, AttributeSet attrs) {
super(context, attrs);
setOnClickListener(this);
moveCountText = (TextView)findViewById(R.id.moveCountView);
}
@Override
public void onClick(View v){
moves++;
message="Move Count: "+ moves;
moveCountText.setText(message);
moveCountText.invalidate();
GameEngine.getInstance().setNumber(number);
}
public void setNumber(int number){
this.number = number;
}
}
麻烦的是,setText说视图是空的(空对象),但我不知道为什么。这是textView XML。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Move count: 0"
android:id="@+id/moveCountView"
android:layout_marginLeft="100dp"
android:layout_marginStart="114dp"
android:layout_marginTop="450dp"/>
我的胜利活动也是如此,错误是意图是一个空对象
public void checkGame(){
int [][] sudGrid = new int[9][9];
for( int x = 0 ; x < 8 ; x++ ){
for( int y = 0 ; y < 8 ; y++ ){
sudGrid[x][y] = getItem(x,y).getValue();
}
}
if( SudokuChecker.getInstance().checkSudoku(sudGrid)){
Toast.makeText(context, "Congratulations!", Toast.LENGTH_LONG).show();
// opens victory screen
Intent nextScreen = new Intent(getApplicationContext(), VictoryActivity.class);
startActivity(nextScreen);
}
}
以下是错误消息
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at sudoku.view.buttonsgrid.NumberButton.onClick(NumberButton.java:33)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
和XML
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Move count: 0"
android:id="@+id/moveCountView"
android:layout_marginLeft="100dp"
android:layout_marginStart="114dp"
android:layout_marginTop="450dp"/>
答案 0 :(得分:0)
每次向文本设置文本时,moveCountText都为空。
更改此内容
setOnClickListener(this);
moveCountText =(TextView)findViewById(R.id.moveCountView);
以 - 强>
moveCountText =(TextView)findViewById(R.id.moveCountView);
moveCountText.setOnClickListner(this);
并实现View.OnClickListner 会为你工作:)