当我尝试做的时候:button.setHeight(900)
因此发生了以下错误:
java.lang.RuntimeException:无法启动活动 java.lang.NullPointerException:尝试调用虚方法'void android.widget.Button.setHeight(int)'在空对象引用上 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483) 在android.app.ActivityThread.access $ 900(ActivityThread.java:153)at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1349) 在android.os.Handler.dispatchMessage(Handler.java:102)at android.os.Looper.loop(Looper.java:148)at android.app.ActivityThread.main(ActivityThread.java:5438)at java.lang.reflect.Method.invoke(Native Method)at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:738) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) 引起:java.lang.NullPointerException:尝试调用虚拟 null对象上的方法'void android.widget.Button.setHeight(int)' 参考 com.codeduc.aayushman.apps.htmlviewerpro.MainActivity.onCreate(MainActivity.java:100) 在android.app.Activity.performCreate(Activity.java:6303)at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
请告诉我们如何修理它。
答案 0 :(得分:0)
Any component available in xml must be initialized in the respective activity file. Then only it is availablein the activity scope
Button button = (Button) findViewById(R.id.assetname); //Need to declare
then we can do as follows
button.setHeight(100)
or more logically we can have as follows
int buttonWidth = (int) (screenWidth / 3.0);
RelativeLayout.LayoutParams params = (LayoutParams) button.getLayoutParams();
params.width = buttonWidth;
params.leftMargin = buttonWidth;
button.setLayoutParams(params);
答案 1 :(得分:-1)
您的按钮变量为空,请尝试使用findviewbyId
进行初始化