以编程方式更改边距会导致ClassCastException

时间:2014-03-26 01:36:31

标签: android android-layout classcastexception

我想在隐藏一些元素时调整布局的边距,所以我尝试了这段代码

RelativeLayout mainLayout;
LinearLayout innerLayout;
public void hideInfoarea(){
    mainLayout = (RelativeLayout) findViewById(R.id.mainContainer);
    innerLayout = (LinearLayout) findViewById(R.id.innerLayout);
    mainContainer.removeView(infoLayout);

    //adjust margins
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)innerLayout.getLayoutParams();
    params.setMargins(10, 0, 0, 10);
    innerLayout.setLayoutParams(params);
}

最初innerLayout的边距为10,0,0,100,我打算在infoLayout remotion之后更改10, 0,0,10中的边距,但不幸的是我得到了跟随错误

 java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
            at com.myapp.test.Myactivity.hideInfoarea(Myactivity.java:371)
            at com.myapp.test.Myactivity.switchBoxStatus(Myactivity.java:360)
            at com.myapp.test.Myactivity.onOptionsItemSelected(Myactivity.java:256)
            at android.app.Activity.onMenuItemSelected(Activity.java:2600)
            at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:372)
            at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1012)
            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
            at com.android.internal.view.menu.ActionMenuView.invokeItem(ActionMenuView.java:546)
            at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:115)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)

innerLayout在我的xml中是LinearLayout,而不是RelativeLayout。所以我不明白问题的原因

1 个答案:

答案 0 :(得分:1)

您可以阅读android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams。 @dcharms是对的,你应该这样做:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) innerLayout.getLayoutParams();  

因为包含innerLayout父视图RelativeLayout而不是LinearLayout。 如果你成功,请告诉我。