所以有一些方法可以解釋,我會盡力涵蓋所有這些方法。
EditText有多個構造函數。您重寫的那個要求您作爲開發人員爲代碼中的其他實例使用設置屬性。所以你實際上可以從這個類中調用setText(someString),或者因爲這個方法是公共的,它直接調用你的類的一個實例。
如果覆蓋包含一個屬性集中的構造,
EditText(Context, AttributeSet)
您可以使用您的組件作爲XML佈局的一部分,並在其上設置的屬性存在,如果它是另一個的EditText(只要你打電話super(context,attributeSet)。如果你想在上面定義你自己的自定義屬性,那麼你實際上很簡單。
在你的項目層次結構中,你應該有或需要創建一個名爲「res/values」的文件夾應該創建一個名爲attr.xml的文件。
<declare-styleable name="myCustomComponents">
<!-- Our Custom variable, optionally we can specify that it is of integer type -->
<attr name="myCustomAttribute" format="integer"/>
...
<!-- as many as you want -->
</declare-styleable>
現在在使用AttributeSet的新構造函數中,可以讀取此新屬性「myCustomAttribute」。
public CustomEditText(Context context, AttributeSet set) {
super(context, set);
// This parses the attributeSet and filters out to the stuff we care about
TypedArray typedArray = context.obtainStyledAttributes(R.stylable.myCustomComponents);
// Now we read let's say an int into our custom member variable.
int attr = typedArray.getInt(R.styleable.myCustomComponents_myCustomAttribute, 0);
// Make a public mutator so that others can set this attribute programatically
setCustomAttribute(attr);
// Remember to recycle the TypedArray (saved memory)
typedArray.recycle();
}
既然我們已經宣佈我們的新屬性,並有安裝程序代碼讀它,我們實際上可以使用它編程或XML佈局。所以我們可以說你在文件中的XML佈局,layout.xml
<ViewGroup
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.my.apk.package"
>
...
<com.my.full.apk.package.CustomEditText
android:id="@+id/custom_edit"
...
custom:myCustomAttribute="12"
/>
...
</ViewGroup>
所以在這方面我們創造像正常的佈局,但是請注意,我們宣佈一個新的XML命名空間。這是爲你的新組件和你的apk。所以在這種情況下,正在使用「自定義」,它會在您定義的樣式中查找新參數。通過使用attr.xml執行之前的步驟,您已將「myCustomAttribute」聲明爲http://schemas.android.com/apk/res/com.my.apk.package名稱空間之外的組件屬性。之後,由您來決定您想要公開的屬性以及這些屬性的實際含義。希望有所幫助。
爲什麼你需要像'custom:myCustomAttribute'中那樣使用'custom'?我可以重命名這個像'xyz:custom:myCustomAttribute'嗎? – mrid 2017-11-04 07:54:31