0

我有一个CustomView扩展类LinearLayout。我有另一个类CustomElement也扩展了LinearLayout. 当我尝试在 XML 中使用我的类时,什么都没有出现。

这是我的自定义视图类:

private static int NUMBER_OF_ELEMENTS = 4;

public CustomView(final Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

private void init(Context context) {
        // get size for each element
    int width = getWidth() / NUMBER_OF_ELEMENTS;
    int height = getHeight() / NUMBER_OF_ELEMENTS;

    for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
        CustomElement element = new CustomElement(context);
        addView(element, width, height);
    }
}

这是我的自定义元素类:

public CustomElement(final Context context) {
    super(context);
    m_context = context;
    init(context);
}

private void init(Context context) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.custom_elem, this);
}

当我现在尝试CustomView在 XML 中添加我的时,它不显示任何内容。这是我的 XML 代码:

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/layout_mainleft"
   android:layout_width="match_parent"
   android:layout_height="match_parent" >

   <com.package.views.CustomView
      android:id="@+id/layout_elements"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true" />

 </RelativeLayout>

我错过了什么吗?任何帮助表示赞赏!

4

2 回答 2

1

I was able to resolve the question with the help of Luksprog!

The problem was, that I was overwriting the onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) method without calling the super method! Therefore it didn't work!

Thanks again to Luksprog at this point.

于 2012-12-17T19:22:08.333 回答
0

据我所知,要创建自定义布局,您应该扩展 ViewGroup,并且您必须覆盖方法 protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4)。在这里你实现你的逻辑并放置你的customView。如果您只是扩展 LinearLayout 并且不以某种方式更改其行为,为什么要扩展它?

于 2012-12-17T10:35:08.603 回答