自定义视图中的自定义视图Group不可见,如何显示?或者有更好的方法可以做到这一点吗?
没有编译或运行时错误,但视图没有显示在viewGroup中,它应该像其他视图一样用颜色填充区域,但它是白色的,视图的颜色没有显示在CustomLayout 内部
xml代码,前两个视图显示没有问题,但嵌套在CustomLayout内部的第三个视图没有显示,只有白色区域,内部的视图不可见
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) {
}
}
自定义视图中的自定义视图组不可见,如何获取出现?
包装子级的父级CustomLayout
有一个空的onLayout()
方法,使子级不出现。这个方法在ViewGroup
中很重要,因为小部件使用它来放置其子级。因此,您需要为这个方法提供一个实现来放置子级(通过在每个具有适当位置的子级上调用layout()
方法)。由于CustomLayout
扩展了FrameLayout
,您可以直接调用超级方法来使用FrameLayout
的实现,或者更好地删除重写的方法(实现它有原因吗?)。