如何使用 Android 的 java 在 LinearLayout 上设置 marginTop?
我正在尝试使用 java 为我的 Android 应用程序设置 LinearLayout 的 marginTop 。我一直在“强制退出”。这是我的代码:
LinearLayout lay = (LinearLayout) findViewById(R.id.linearLayout1);
LayoutParams lp = lay.getLayoutParams();
lp.setMargins(10, 20, 30, 40);
lay.setLayoutParams(lp);
我做错了什么?
这就是我在 logcat 中得到的信息:
01-12 18:50:16.237: D/AndroidRuntime(482): Shutting down VM
01-12 18:50:16.237: W/dalvikvm(482): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
01-12 18:50:16.237: E/AndroidRuntime(482): Uncaught handler: thread main exiting due to uncaught exception
01-12 18:50:16.247: E/AndroidRuntime(482): java.lang.RuntimeException: Unable to start activity ComponentInfo{nu.katterevyn/nu.katterevyn.StartActivity}: java.lang.NullPointerException
01-12 18:50:16.247: E/AndroidRuntime(482): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
01-12 18:50:16.247: E/AndroidRuntime(482): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
01-12 18:50:16.247: E/AndroidRuntime(482): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
谢谢!
I am trying to set the marginTop of a LinearLayout with java for my Android app. I keep on getting "force quits" all the time. This is my code:
LinearLayout lay = (LinearLayout) findViewById(R.id.linearLayout1);
LayoutParams lp = lay.getLayoutParams();
lp.setMargins(10, 20, 30, 40);
lay.setLayoutParams(lp);
What am I doing wrong ?
This is what i get in my logcat:
01-12 18:50:16.237: D/AndroidRuntime(482): Shutting down VM
01-12 18:50:16.237: W/dalvikvm(482): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
01-12 18:50:16.237: E/AndroidRuntime(482): Uncaught handler: thread main exiting due to uncaught exception
01-12 18:50:16.247: E/AndroidRuntime(482): java.lang.RuntimeException: Unable to start activity ComponentInfo{nu.katterevyn/nu.katterevyn.StartActivity}: java.lang.NullPointerException
01-12 18:50:16.247: E/AndroidRuntime(482): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
01-12 18:50:16.247: E/AndroidRuntime(482): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
01-12 18:50:16.247: E/AndroidRuntime(482): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用下面的代码
谢谢!
Use the below code
Thanks!
将 LayoutParams 更改为 LinearLayout.LayoutParams 和 lp.setMargins(0, top, 0, 0); 。另外,指定边距单位,例如:
dp, px
。Change
LayoutParams
toLinearLayout.LayoutParams
andlp.setMargins(0, top, 0, 0);
. Also, specify a unit for your margins ex:dp, px
.要将单位指定为 dp 您可以:
To specify unit to dp You can: