我正在尝试以编程方式将imageViews添加到Custom RelativeLayout。问题是由于某种原因,自定义RelativeLayout的childViews不可见。我做错了什么?
public class MyViewGroup extends RelativeLayout{
Context mContext;
public MyViewGroup(Context context) {
super(context);
mContext = context;
init();
}
public MyViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}
public MyViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
init();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
void init()
{
for(int i=0; i<2; i++)
{
ImageView myImage = new ImageView(mContext);
if(i==0)
myImage.setBackgroundColor(Color.CYAN);
else
myImage.setBackgroundColor(Color.MAGENTA);
myImage.setId(i);
RelativeLayout.LayoutParams params= new LayoutParams(50+i*70, 50+i*70);
myImage.setLayoutParams(params);
ImageView sImage = new ImageView(mContext);
if(i==0)
sImage.setBackgroundColor(Color.RED);
else
sImage.setBackgroundColor(Color.GREEN);
RelativeLayout.LayoutParams p= new LayoutParams(200+i*70, 200+i*70);
p.addRule(RelativeLayout.ALIGN_TOP | RelativeLayout.ALIGN_LEFT, myImage.getId());
sImage.setLayoutParams(p);
addView(myImage);
addView(sImage);
}
}
}
内部布局file.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<user.com.MyViewGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
我错过了什么?
最好的问候
编辑:
RelativeLayout.LayoutParams params= new LayoutParams(200+i*70, 200+i*70);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
myImage.setLayoutParams(params);
ImageView sImage = new ImageView(mContext);
sImage.setBackgroundColor(Color.RED);
RelativeLayout.LayoutParams p= new LayoutParams(20+i*70, 20+i*70);
p.addRule(RelativeLayout.CENTER_IN_PARENT);
p.addRule(RelativeLayout.ALIGN_BOTTOM, myImage.getId());
sImage.setLayoutParams(p);
addView(myImage);
addView(sImage);
答案 0 :(得分:0)
您错过了致电super.onLayout(changed, l, t, r, b);
,@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
负责为其子女分配职位。在ViewGroup的具体实现中,如果默认实现对您来说足够,则可以避免重写此方法。如果您决定扩展ViewGroup,则必须提供实现,因为它被声明为abstract。在你的情况下你可以摆脱
{{1}}