我正在使用我正在使用的返回null的ImageView。问题似乎与findViewById有关,并且当我为imageView采用getX()时会导致问题。我已经尝试了一切,仍然无法让它工作。任何帮助将不胜感激!
的xml:
ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:src="@drawable/character"
android:id="@+id/character"
android:scaleType="fitCenter"
android:clickable="false"
android:longClickable="false" /
爪哇: 包fozard.backuptestapp;
public class Play extends AppCompatActivity {
private GameThread thread;
private float charX=0;
ImageView character;
public void setCharacter(ImageView character) {
this.character = character;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
}
@Override
protected void onStart(){
super.onStart();
thread=new GameThread();
thread.setRunning(true);
thread.start();
}
public boolean onTouchEvent(MotionEvent event){
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
thread.setMovementSpeed(5);
thread.setMoving(true);
break;
case MotionEvent.ACTION_UP:
thread.setMoving(false);
}
return true;
}
public void updateCharPos(float movementSpeed){
Log.d("Updating", "Should be able to update");
character = (ImageView)findViewById(R.id.character);
charX = character.getX();
System.out.print(charX);
}
}
堆栈跟踪:
11-24 09:32:32.918 16706-16706/fozard.backuptestapp D/Updating: Should be able to update
11-24 09:32:32.923 16706-16706/fozard.backuptestapp D/AndroidRuntime: Shutting down VM
11-24 09:32:32.923 16706-16706/fozard.backuptestapp W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41cbc700)
11-24 09:32:32.933 16706-16706/fozard.backuptestapp E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at fozard.backuptestapp.Play.updateCharPos(Play.java:71)
at fozard.backuptestapp.GameThread$1.run(GameThread.java:88)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
ImageButton pauseButton = (ImageButton) findViewById(R.id.pausebutton);
更改此
ImageView pauseButton = (ImageView ) findViewById(R.id.character);
您使用了错误的ID和错误的小部件。 首先阅读教程。
答案 1 :(得分:0)
从我在xml中看到的内容,你为ImageView使用了错误的id,应该是:
ImageView pauseButton = (ImageView) findViewById(R.id.character);
你还必须为xml和Javacode(ImageView)使用相同的类