我想在 Android 上创建一个自定义的 View
。我试图尽可能简单地做到这一点,并创建了一个几乎为空的类 MyView
并在我的 LinearLayout
中使用了它,但应用程序在启动时以“强制关闭”失败。我怎样才能做一个简单的自定义 View
?根据 Building Custom Components,如果我不覆盖 onMeasure()
,View
的大小为 100x100。
public class MyView extends View {
public MyView(Context context) {
super(context);
}
}
我在 LinearLayout
中使用它:
<view
class="com.example.MyView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.0" />
我做错了什么?
如果我使用 itemon 建议的构造函数和对父类(super class)的相应调用。然后“强制关闭”消失了,但是我的 LinearLayout
坏了,MyView
之后的组件没有显示。
这是我的main.xml
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.0"
android:background="#f00"
android:text="Hello"
/>
<view
class="com.example.MyView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.0"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.0"
android:background="#00f"
android:text="World"
/>
</LinearLayout>
最佳答案
也许你可以像这样定义另一个构造函数方法:
public MyView(Context context, AttributeSet attrs)
android 框架将尝试使用您从上面的构造函数中查看的 View 来构建 UI。
关于android - 如何创建一个简单的自定义 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4439456/