如何在自定义viewGroup / Layout中放置自定义视图

时间:2014-02-26 13:01:03

标签: android user-interface android-custom-view

自定义viewGroup内的自定义视图不可见,我该如何让它显示出来? 或者有更好的方法来做到这一点吗?

没有编译或运行时错误,但视图没有显示在viewGroup中,它应该像其他视图一样填充区域但是它是白色的,并且视图的颜色没有显示在CustomLayout内部

xml代码,前2个视图显示没有问题,但是嵌套在CustomLayout内的第3个视图没有显示,只是白色区域,里面的视图不可见

CustomViewOne是一个单独的类文件,CustomViewTwo和CustomViewThree都作为静态内部类嵌套在MainActivity类中,而CustomLayout是一个单独的文件

<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >

<com.example.customviewexample.CustomViewOne
    android:layout_width="100dp"
    android:layout_height="50dp" />

<view 
    class="com.example.customviewexample.MainActivity$CustomViewTwo"
    android:layout_width="100dp"
    android:layout_height="50dp" />

<com.example.customviewexample.CustomLayout
    android:layout_width="100dp"
    android:layout_height="50dp">

    <view 
        class="com.example.customviewexample.MainActivity$CustomViewThree"
           android:layout_width="match_parent"
           android:layout_height="match_parent" />

</com.example.customviewexample.CustomLayout>

</LinearLayout>

这里是CustomViewThree的代码,与其他自定义视图一样简单,它只是用颜色填充区域,它嵌套在MainActivity中,因此您必须使用MainActivity $ CustomViewThree来访问它。

public static class CustomViewThree extends View {

public CustomViewThree(Context context) {
    super(context);

}

public CustomViewThree(Context context, AttributeSet attrs) {
    super(context, attrs);

}

public CustomViewThree(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

}

@Override
protected void onDraw(Canvas canvas) {

    super.onDraw(canvas);

    canvas.drawColor(Color.GREEN);
}

}

这是CustomLayout类的代码

public class CustomLayout extends FrameLayout {

public CustomLayout(Context context) {
    super(context);
   init(context);
}

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

public CustomLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
   init(context);
}

public void init(Context context) {

}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {

}

}

1 个答案:

答案 0 :(得分:4)

  

自定义viewGroup内的自定义视图不可见,我该如何获取它   出现?

包裹孩子的父CustomLayout有一个空的onLayout()方法,使孩子不会出现。此方法在ViewGroup中很重要,因为窗口小部件使用它来将子项放在其中。因此,您需要为此方法提供一个实现来放置子项(通过在每个子项上调用适当位置的layout()方法)。当CustomLayout扩展FrameLayout时,您可以调用super方法来使用FrameLayout的实现,甚至可以更好地删除重写方法(是否有理由实现它?)。

相关问题