Assigning a custom class to an existing class in Silver (Android)

Hi,

I have made a custom ImageView class like this.

public class yazDice: android.widget.ImageView

I am wanting to assign this custom ImageView to an ImageView in MainActivity. I am doing it like this

let diceOne = self.findViewById(R.id.ivDiceOne) as! yazDice

The XML looks like this

<ImageView
    android:id="@+id/ivDiceOne"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/dice1"
    android:layout_marginTop="16dp"
    android:layout_marginLeft="24dp" />

All compiles OK but when it runs it says it cannot assign ImageView as yazDice.

Any ideas why?

Thanks!

The xml is wrong. IIRC you need to do <com.mynamesspace.yazDice android:id="....

awesome! can you give an example what that would look like?

<com.mynamesspace.yazDice
android:id="@+id/ivDiceOne"
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:src="@drawable/dice1"
android:layout_marginTop=“16dp”
android:layout_marginLeft=“24dp” />

like this?

Yes. See also https://developer.android.com/guide/topics/ui/custom-components.html

If you use swift make sure you use the default namespace (project options) + typename.

1 Like

Thank you very much Carlo.

so like this?

<org.fsxp.yazandroid.yazDice
	android:id="@+id/ivDiceOne"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:src="@drawable/dice1"
	android:layout_marginTop="16dp"
	android:layout_marginLeft="24dp" />

or does it need the com.

also, do I need to add the class here?

RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
class=“org.fsxp.yazDice”
android:layout_width=“match_parent”
android:layout_height=“match_parent” >

I only ask because it causing Water to crash and I can’t see any of the errors (I have reported this to Marc)

Thanks!

FTR, that crash seems to be unrelated, it’s an uncaught exception in the Java debugger.

just to update… the layout above is correct “org.fsxp.yazandroid.yazDice”. Seems the device I was testing it on wasn’t OK. I tested on a different device and got past the previous error. :slight_smile:

2 Likes