3

I want to set some properties for the first ImageView element, and then inherit the properties in other elements.

The following does not work, but probably there is something similar?

<ImageView android:id="@+id/myimage" android:layout_height="100dp" android:layout_width="100dp"/> <ImageView android:id="@+id/myimage2" android:layout_height="@myimage/layout_height" android:layout_width="@myimage/layout_width"/> 
6
  • you will have to create a resource in dimens.xml which will come under res>values and use that for whichever xml element you want Commented Jul 27, 2017 at 7:33
  • So I cannot make cross references inside the same file? Commented Jul 27, 2017 at 7:36
  • You can make style for it. Commented Jul 27, 2017 at 7:37
  • 1
    You could use a dimension e.g. in res/values/dimens.xml add <dimen name="myimageheight">100dp</dimen> along with android:layout_height="@dimens/myimageheight" (repeat this where needed). Commented Jul 27, 2017 at 7:37
  • What is the purpose of doing this? If it is for reusability, take a look at this. Commented Jul 27, 2017 at 7:40

1 Answer 1

2

You can't do that in that way, but you have 2 options here:

Option 1: declare the value as a dimension and the use it:

Declare two values for height and width in dimens.xml that can be found at res/values.

<dimen name="image_width">100dp</dimen> <dimen name="image_height">100dp</dimen> 

Then use them in your xml like this:

<ImageView android:id="@+id/myimage2" android:layout_height="@dimen/image_height" android:layout_width="@dimen/image_width"/> 

Option 2: Create a style associated with your ImageView:

First thing to do is to create the style for your views and place it in styles.xml that can be found at res/values.

<style name="my_image_view_style"> <item name="android:layout_height">100dp</item> <item name="android:layout_width">100dp</item> </style> 

Add your created style to your ImageView:

<ImageView android:id="@+id/myimage2" style="@style/my_image_view_style"/> 
Sign up to request clarification or add additional context in comments.

2 Comments

<style> looks promising. But trying to use it states "attribute is missing the android namespace". Where do I have to put those styles? In the same file, or in a different one?
You need to declare the in the styles.xml file in resources. I'll edit my answer to make it easier to understand.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.