android - 如何创建一个简单的自定义 View ?

标签 android view android-linearlayout custom-view

我想在 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/

相关文章:

android - 彼此后面的两个 TextView,仅椭圆化第一个,第二个始终可见

android - 如何使按钮在布局中右对齐?

android - 通过 sql 循环将多个 TextView 动态添加到 TableRow

java - 为什么我的编译器在不应该出现 NullPointerException 的情况下出现?

java - 安卓代码质量

java - Android隐藏状态栏、兼容性

android - 在 UI 中使用线程以加载网页的 Android 最佳实践?

Python 获取 SettingWithCopyWarning - iloc 与 loc - 无法弄清楚原因

PostgreSQL 查看嵌入的 if 语句

在 codeigniter 的另一个 View 中加载 View 时,HTML 元素放错了位置