簡體   English   中英

如何在布局xml中使用自定義視圖

[英]How to use a custom view in layout xml

我已經在Main Activity的onCreate()方法中設置了一個自定義視圖。

像這樣:

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

我的問題是。 如何在xml中引用視圖,以便可以將其與其他控件一起放入linearlayout中?

假設您的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);

setContentView(“此處放置您的xml布局”)

在.xml布局中,只需簡單地添加ur View:

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

您將必須在XML文件中添加自定義視圖,如下所示:

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

之后,您可以通過其ID訪問此視圖,就像對其他任何視圖所做的一樣

首先,您必須重寫超類的任何構造函數。 如果您不這樣做,將會收到運行時錯誤,並且您的活動將永遠無法打開。 然后,您應該使用完全合格的類名稱,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM