【发布时间】:2026-01-04 09:45:02
【问题描述】:
我想在 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 建议的构造函数以及对超类的相应调用。然后“强制关闭”就没有了,但是我的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>
【问题讨论】:
-
你可以在这里咨询一个好的样本:http://www.sgoliver.net/blog/?p=1457
-
我有类似的需求..你有你需要的吗。 .share一些代码plz
标签: android view android-linearlayout custom-view