自定义布局在安卓自定义、布局

2023-09-08 08:42:13 作者:撩人不撩心

有谁知道如何在Android中实现自定义布局?

Does anyone know how to implement custom layouts in android?

我有CustomLayout类。

I have CustomLayout class.

CustomLayout extends LinearLayout

与构造公共CustomLayout(上下文的背景下)公共CustomLayout(上下文的背景下,AttributeSet中的ATTRS)

我也有一个XML布局(的example.xml)

I also have a xml layout (example.xml)

<com.myproject.layout.CustomLayout 
    android:id="@+id/cl_main"    
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

   <Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="inside button" />

</com.myproject.layout.CustomLayout>

当我设置的内容视图中我的活动

When I set the content view in my activity

    setContentView(R.layout.example);

我的全球布局是膨胀并显示,但内键是不是里面的布置... 任何想法?

My Global layout is inflated and is showed, but the "inner button" is not inside the layout... Any ideas?

推荐答案

我发现你必须重写此方法。

I found that you must override this method.

public void addView(View child, android.view.ViewGroup.LayoutParams params)
{
    //... 
    llContainer.addView(child, fillParentLayoutParams);
    //...
}

其中llContainer是其中次应该放置的布局。 这种方法被充气来填充你的视图的XML定义。

where llContainer is the layout where the views should be placed. this method is called by the inflater to populate your view with the xml definitions.