自定义viewGroup内的自定义视图不可见,如何让它显示出来?
或者有更好的方法来做到这一点吗?
没有编译或运行时错误,但视图没有显示在viewGroup中,它应该像其他视图一样填充区域但是它是白色的,并且视图的颜色没有显示在CustomLayout内部
xml代码,前2个视图显示没有问题,但是嵌套在CustomLayout内部的第3个视图没有显示,只是白色区域,里面的视图不可见
CustomViewOne是一个单独的类文件,CustomViewTwo和CustomViewThree都作为静态内部类嵌套在MainActivity类中,而CustomLayout是一个单独的文件
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
android:layout_width="100dp"
android:layout_height="50dp" />
class="com.example.customviewexample.MainActivity$CustomViewTwo"
android:layout_width="100dp"
android:layout_height="50dp" />
android:layout_width="100dp"
android:layout_height="50dp">
class="com.example.customviewexample.MainActivity$CustomViewThree"
android:layout_width="match_parent"
android:layout_height="match_parent" />
这里是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) {
}
}
解决方法:
custom view inside of a custom viewGroup not visible, how can I get it
to show up?
包装子项的父ContentLayout有一个空的onLayout()方法,该方法不会显示子项.此方法在ViewGroup中很重要,因为窗口小部件使用它来将子项放在其中.因此,您需要为此方法提供一个实现来放置子项(通过在每个子项上使用适当的位置调用layout()方法).由于CustomLayout扩展了FrameLayout,你可以调用super方法来使用FrameLayout的实现,甚至可以更好地删除重写方法(是否有理由实现它?).
标签:android,user-interface,android-custom-view
来源: https://codeday.me/bug/20190624/1279867.html