扩展RelativeLayout

时间:2011-07-22 10:48:53

标签: android relativelayout custom-view

这是我在创建具有可自定义的过度滚动的ListView时所做的更多工作。

我想创建一个扩展RelativeLayout的Custom元素,但是添加子视图并不能正常工作。代码似乎正确,但视图看起来有些疯狂。

    underscrollEdge = new ImageView(context);
    underscrollEdge.setImageResource(R.drawable.underscroll_edge);
    underscrollGlow = new ImageView(context);
    underscrollGlow.setImageResource(R.drawable.underscroll_glow);
    overscrollGlow = new ImageView(context);
    overscrollGlow.setImageResource(R.drawable.overscroll_glow);
    overscrollEdge = new ImageView(context);
    overscrollEdge.setImageResource(R.drawable.overscroll_edge);

    RelativeLayout.LayoutParams topLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    topLayout.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    addView(underscrollEdge, topLayout);
    addView(underscrollGlow, topLayout);        

    RelativeLayout.LayoutParams bottomLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    bottomLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    addView(overscrollGlow, bottomLayout);      
    addView(overscrollEdge, bottomLayout);  

奇怪的是,这给了我(我将相对布局设置为黑色以显示边缘和发光):

正如你所看到的,顶部边缘漂浮在不知名的中间,底部的光线缩小到一个很小的尺寸......那真是太棒了?

1 个答案:

答案 0 :(得分:0)

喜欢写下这个问题有助于我解决问题:

    RelativeLayout.LayoutParams topLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    topLayout.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    addView(underscrollGlow, topLayout);        
    topLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    topLayout.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    addView(underscrollEdge, topLayout);    

    RelativeLayout.LayoutParams bottomLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    bottomLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    addView(overscrollGlow, bottomLayout);      
    bottomLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    bottomLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    addView(overscrollEdge, bottomLayout);  

对两个组件使用相同的LayoutParams会让事情变得奇怪。看起来很麻烦,但确实解决了问题。