如何使用里面的元素创建子视图?

时间:2013-05-19 19:47:55

标签: android view android-linearlayout parent-child

我通过谷歌找到了this video,通过使用onClick添加或删除子视图,通过创建子视图演示了动画过渡。作为学习过程的一部分:我接受了代码,将其分解并进行了一些更改(我不是复制和粘贴程序员)。

我的问题是:如何在创建子视图时向其添加TextViewButton和其他各种元素?

(如果您感兴趣,请从谷歌下载项目:full project

以下是我在活动中的内容:

/**
 * Custom view painted with a random background color and two different sizes which are
 * toggled between due to user interaction.
 */
public class ColoredView extends View {

    private boolean mExpanded = false;

    private LinearLayout.LayoutParams mCompressedParams = new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, 50);

    private LinearLayout.LayoutParams mExpandedParams = new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, 200);

    private ColoredView(Context context) {

        super(context);

        int red = (int)(Math.random() * 128 + 127);
        int green = (int)(Math.random() * 128 + 127);
        int blue = (int)(Math.random() * 128 + 127);
        int color = 0xff << 24 | (red << 16) |
                (green << 8) | blue;
        setBackgroundColor(color);

        setLayoutParams(mCompressedParams);


        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Size changes will cause a LayoutTransition animation if the CHANGING transition is enabled
                setLayoutParams(mExpanded ? mCompressedParams : mExpandedParams);
                mExpanded = !mExpanded;
                requestLayout();

            }
        });
    }
}

我也在onCreate方法中显示动画

LayoutTransition transition = eventContainer.getLayoutTransition();
    transition.enableTransitionType(LayoutTransition.CHANGING);

这是我的XML,其LinearLayout所有子视图都在其中创建:

<LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:animateLayoutChanges="true"
            android:id="@+id/eventContainer">
    </LinearLayout>

通过向linearlayout添加按钮或edittext,它将其视为一个全新的视图,每个只允许一个对象。有没有办法可以将一堆物体撞到那个布局?

我对获取context视图和布局的概念感到有点困惑......我可能在这里误解了它。

1 个答案:

答案 0 :(得分:1)

你不能,至少不能在你当前的代码中。

您的ColoredView课程目前正在扩展View,该课程不支持拥有自己的子视图。如果要向其添加子视图,则必须创建一个扩展ViewGroup(或任何ViewGroup的子类)的类。

您的课程延伸ViewGroup后,您可以简单地使用addView()方法添加视图,并通过传递LayoutParams来对齐它们(您也可以创建自定义LayoutParams你的观点需要复杂的定位。

相关问题