2

经过大量研究,我没有找到如何在 Xml 中设计自定义组件。

我知道我必须创建一个继承 View 的类,但在构造函数中我想引用一个 xml,我在其中使用一些 android 组件来设计我的对象。

这是我放在布局文件夹中的 chronometer.xml 文件中的视图内容:

<?xml version="1.0" encoding="utf-8"?>
<com.fr.loroux.minuteursimple.Chronometer
 xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/customChronometer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/hours"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00" />

    <TextView
        android:id="@+id/minutes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00" />

    <TextView
        android:id="@+id/seconds"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00" />

</com.fr.loroux.minuteursimple.Chronometer>

但是现在我如何通过构造函数类引用它?这是不可能的 ?

谢谢你的帮助。

4

1 回答 1

2

您要做的是复合视图。要引用您的 xml 布局,请使用构造函数中的下一个代码:

LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.chronometer, this, true);

有关如何创建视图的详细信息,请参阅创建复合视图

于 2013-07-30T21:13:10.213 回答