15

I've created a custom view with attributes. Is there a way to use those attributes with android tools in Android studio?

for example :

<MyOwnCoolView
    android:layout_width="96dp"
    android:layout_height="96dp"
    android:padding="3dp"
    tools:dividerAngle="2"/>

Where the attr file is :

<resources>
<declare-styleable name="MyOwnCoolView">
    <attr name="dividerAngle" format="float"/>
</declare-styleable>

R. Zagórski
  • 20,020
  • 5
  • 65
  • 90
RCB
  • 2,253
  • 2
  • 25
  • 49
  • Why would you use the tool namespace? You can use the "http://schemas.android.com/apk/res-auto" namespace. – natario Oct 27 '15 at 14:54
  • 1
    to have a place holder with value. to see how it all looks in the design view. later during run-time this view will get various values. – RCB Oct 27 '15 at 14:56
  • As far as I know the design preview should work with "schemas.android.com/apk/res-auto" too, be sure to retrieve the values in the class constructor. – natario Oct 27 '15 at 14:59
  • Of course it works, but the dummy value stays there also for the release. Using tool you don't have to worry about "cleaning" the dummy data – RCB Oct 27 '15 at 15:01
  • Ok I got it finally :) you should edit your question to make this clear. What happens if you set tools:dividerAngle ? Nothing? – natario Oct 27 '15 at 15:04

3 Answers3

6

My opinion is that you can't.

There's an official, though very old, page here that quotes:

Designtime attributes can only be used for framework resources, not custom attributes at this point.

natario
  • 24,954
  • 17
  • 88
  • 158
2

I was looking for the same thing for a while now. Decided to make a library that allows one to do it. https://github.com/giljulio/sneakpeek

Gil Julio
  • 812
  • 1
  • 9
  • 18
1

I've written a tiny library that allows you define design-time attributes for your views: https://github.com/paulmanta/app-tools-attrs

Firstly, you have to declare separate attributes that you want to as at design-time:

<declare-styleable name="MyWidget">
    <attr name="title" format="string"/>
    <attr name="tools_title" format="string"/>
</declare-styleable>

Finally, when you initialize your custom view use the AppToolsAttrs class instead of accessing attributes directly from a TypedArray:

AppToolsAttrs.getString(a, isInEditMode(), R.styleable.MyWidget_title, R.styleable.MyWidget_tools_title)

You can then use your design-time attributes like this:

<com.myapplication.MyWidget
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tools_title="Lorem ipsum"
    app:title="@string/real_title"/>

Gil already posted an answer with a different library that allows you do this. His implementation is really smart and it allows you to use the actual tools: namespace without having to duplicate attributes. Unfortunately, it's incompatible with Android Studio's auto-complete feature.

Paul Manta
  • 30,618
  • 31
  • 128
  • 208