如何在布局xml中使用自定义视图

时间:2012-08-10 10:26:52

标签: android xml

我已经创建了一个自定义视图,我在主活动中的onCreate()方法中进行了设置。

像这样:

compassView = new CompassView(this);
setContentView(compassView);

我的问题是。如何在xml中引用视图,以便将其与其他控件一起放在linearlayout中?

4 个答案:

答案 0 :(得分:0)

假设您的CompassView是一个放在Package中的类,

com.android.sample

创建这样的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" >

  <com.android.sample.CompassView 
       android:id="@+id/compassview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"

      />
</LinearLayout>

现在和setContentView(R.layout.xmlname);一样onCreate()

compassView = (CompassView)findViewbyId(R.id.compassview);

答案 1 :(得分:0)

setContentView(“这里放你的xml布局”)

在.xml布局中只需简单添加你的视图:

<com.example.widget.CompassView
            android:id="@+id/..."
            style="@style/..." >
    </com.example.widget.CompassView>

答案 2 :(得分:0)

您必须在xml文件中添加自定义视图,如下所示:

<yourpackagename.yourCustomViewClass
        android:id="@+id/myCustomView" 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

在此之后,您可以通过其ID访问此视图,就像您对其他任何视图

所做的那样

答案 3 :(得分:0)

首先,您必须覆盖超类的任何构造函数。如果不这样做,您将收到运行时错误,并且您的活动将永远不会打开。然后你应该使用完全限定的类名,如下所示:

<your_package_name.your_class_name
   android:id="@+id/mycompass"
   your attributes here
   ...
 />