Kev*_*vik 5 user-interface android android-custom-view
自定义视图组中的自定义视图不可见,我怎样才能让它显示出来?或者有没有更好的方法来做到这一点?
没有编译或运行时错误,但视图没有显示在 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>
Run Code Online (Sandbox Code Playgroud)
这是 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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是 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) {
}
}
Run Code Online (Sandbox Code Playgroud)
自定义视图组内的自定义视图不可见,如何让它显示?
CustomLayout包装孩子的父母有一个空onLayout()方法,使孩子不会出现。此方法在 a 中很重要ViewGroup,因为小部件使用它来将其子项放置在其中。因此,您需要为此方法提供一个实现来放置子项(通过layout()在每个子项上调用适当位置的方法)。作为CustomLayout扩展,FrameLayout您可以只调用 super 方法来使用 的FrameLayout实现,甚至更好地删除重写的方法(有实现它的理由吗?)。
| 归档时间: |
|
| 查看次数: |
2099 次 |
| 最近记录: |