0

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

像这样:

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

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

4

4 回答 4

0

First of all, you must override any constructor of your superclass. If you don't do that you will get a run time error and you activity will never be opened. Then you should use the fully qualified class name like this:

<your_package_name.your_class_name
   android:id="@+id/mycompass"
   your attributes here
   ...
 />
于 2012-08-10T10:35:31.543 回答
0

假设您CompassView是一个放置在名为的包中的类,

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);

于 2012-08-10T10:31:37.903 回答
0

setContentView("这里放你的 xml 布局")

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

<com.example.widget.CompassView
            android:id="@+id/..."
            style="@style/..." >
    </com.example.widget.CompassView>
于 2012-08-10T10:32:00.363 回答
0

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

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

在此之后,您可以通过其 id 访问此视图,就像您对任何其他视图所做的那样

于 2012-08-10T10:32:02.490 回答