如何使用java for Android在LinearLayout上设置marginTop?

时间:2012-01-12 17:57:57

标签: android margin android-linearlayout

我正在尝试使用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)

谢谢!

3 个答案:

答案 0 :(得分:2)

使用以下代码

LinearLayout lay = (LinearLayout) findViewById(R.id.linearLayout1);
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)lay.getLayoutParams();
lp.setMargins(10, 20, 30, 40);
lay.setLayoutParams(lp);

谢谢!

答案 1 :(得分:1)

LayoutParams更改为LinearLayout.LayoutParamslp.setMargins(0, top, 0, 0);。另外,请为您的边距指定一个单位:dp, px

答案 2 :(得分:0)

将单位指定为dp您可以:

DisplayMetrics metrics = new DisplayMetrics();
a.getWindowManager().getDefaultDisplay().getMetrics(metrics);
return (size * metrics.densityDpi) / DisplayMetrics.DENSITY_DEFAULT;