android:SetX和SetY小于API11

时间:2013-12-31 17:37:34

标签: android nullpointerexception

由于仅从API11开始引入setXsetY,因此对于具有api< 11,我已经实现了以下代码:

代码:

      image_boy = (Button) layoutInflater.inflate(R.layout.untouched, null);

      if (Build.VERSION.SDK_INT < 11) //11 is Android 3.0 HoneyComb, 10 is 2.3.3 - 2.3.7
      {

              ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams)  //Line 432 
              image_boy.getLayoutParams(); //
                  lp.setMargins((viewWidth - BOY_WIDTH) /2, (viewHeight - BOY_HEIGHT), 0, 0);
                  image_boy.setLayoutParams(lp);  
              }
              else
              {
                  image_boy.setX((viewWidth - BOY_WIDTH) /2); 
                  image_boy.setY(viewHeight - BOY_HEIGHT);            
              }

堆栈:

01-01 01:31:25.100: E/AndroidRuntime(6826): FATAL EXCEPTION: main
01-01 01:31:25.100: E/AndroidRuntime(6826): java.lang.NullPointerException
01-01 01:31:25.100: E/AndroidRuntime(6826):     at com.abc.abc.Game_collecting_view.set_boy(Game_collecting_view.java:432)
01-01 01:31:25.100: E/AndroidRuntime(6826):     at com.abc.abc.Game_collecting_view$2.run(Game_collecting_view.java:624)
01-01 01:31:25.100: E/AndroidRuntime(6826):     at android.os.Handler.handleCallback(Handler.java:587)
01-01 01:31:25.100: E/AndroidRuntime(6826):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-01 01:31:25.100: E/AndroidRuntime(6826):     at android.os.Looper.loop(Looper.java:130)
01-01 01:31:25.100: E/AndroidRuntime(6826):     at android.app.ActivityThread.main(ActivityThread.java:3770)
01-01 01:31:25.100: E/AndroidRuntime(6826):     at java.lang.reflect.Method.invokeNative(Native Method)
01-01 01:31:25.100: E/AndroidRuntime(6826):     at java.lang.reflect.Method.invoke(Method.java:507)
01-01 01:31:25.100: E/AndroidRuntime(6826):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
01-01 01:31:25.100: E/AndroidRuntime(6826):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670)
01-01 01:31:25.100: E/AndroidRuntime(6826):     at dalvik.system.NativeStart.main(Native Method)

问题:

如何处理nullPointerException?

2 个答案:

答案 0 :(得分:1)

您错误地指定了image_boy

image_boy = (Button) layoutInflater.inflate(R.layout.untouched, null);

要么是

image_boy = (Button) findViewById(R.id.image_boy_id);

image_boy = (Button) layoutInflater.inflate(R.layout.untouched, null).findViewById(R.id.image_boy_id);

答案 1 :(得分:1)

getLayoutParams()将返回null,直到视图附加到其父级。 尝试使用其构造函数创建布局参数,而不是使用getLayoutParams()