2013-07-30 37 views
2

經過大量研究,我沒有找到如何在Xml中設計自定義組件。通過xml設計製作自定義組件

我明白,我必須創建一個繼承的看法,但在構造函數中,我想引用一個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> 

但是現在我如何可以參考它通過構造類? 這不可能?

感謝您的幫助。

回答

2

你想要做的是一個複合視圖。要引用您的XML佈局使用下面的代碼在構造函數:

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

欲瞭解更多信息,如何創建您的視圖中看到Create compound view

+2

或更短:'LayoutInflater.from(context).inflate(R.layout.chronometer,this,true);' –

+1

或更短,最後一個'true'參數是可選的,默認爲false。 :) – kcoppock