0
我想创建一个方法,它可以在给定距离的情况下水平移动列表元素。该列表元素是一个RelativeLayout的,所以我做到以下几点:尝试设置列表项目上的边距时出现ClassCastException
// cast View to RelativeLayout
RelativeLayout listLayout = (RelativeLayout) listElement;
// Get layout params
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) listLayout.getLayoutParams();
//set the margins
layoutParams.setMargins(distance,0,0,0);
// ??
listLayout.setLayoutParams(layoutParams);
// Profit!!!
我在调试器中检查,列表项是一个RelativeLayout的,甚至在我投它(只是为了确保)。然而,我得到以下几点:
java.lang.ClassCastException: android.widget.AbsListView$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
我已经尝试了很多变化,并且他们都停止与铸造错误。但我无法弄清楚为什么,因为正在使用RelativeLayout,所以我应该能够调用该方法并取回一个RelativeLayout.LayoutParams对象。
这样的作品,除了setMargins方法消失了。哪种失败的目的。这是否意味着我只能以编程方式设置顶级元素的边距? –
@TomMacdonald我不知道用编程的方式来做它,但可能有一种方法。 在Relativelayout中添加布局是一种方法,但可能有更好的方法。 – ademar111190
@TomMacdonald和你没有setMargins的原因是因为该方法在这个类中声明了'ViewGroup.MarginLayoutParams'这个类扩展了ViewGroup.LayoutParams,并且relativelayout.LayoutParams扩展了ViewGroup.MarginLayoutParams类。 – ademar111190