Does Android studio layout editor shows custom view properties?

孤街醉人 提交于 2019-12-23 07:03:24

问题


I have a compound view which consists of two Buttons and one Text view. I want to edit properties of these child views in the Android Studio Layout Editor but I can't. It only shows basic properties but no properties of my custom view.

Does the Android Studio Layout Editor only shows limited number of properties set by default? Is it possible to edit properties of my custom view from there, without manually editing the XML files?

Thanks in advance!!


回答1:


As described in http://developer.android.com/training/custom-views/create-view.html#customattr you have to add a new ressource (res/values/attrs.xml).

<resources>
   <declare-styleable name="PieChart">
       <attr name="showText" format="boolean" />
       <attr name="labelPosition" format="enum">
           <enum name="left" value="0"/>
           <enum name="right" value="1"/>
       </attr>
   </declare-styleable>
</resources>

Within your View you have to reference this new ressource

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews">
     <com.example.customviews.charting.PieChart
         custom:showText="true"
         custom:labelPosition="left" />
</LinearLayout>

Now you should see the properties in the editor.




回答2:


If you customize a View with custom attributes, you need to use your own namespace to set your custom attributes.

First, set namespace in the root view of your layout like this:

xmlns:sidespinner="http://schemas.android.com/apk/res-auto"

Since custom attribute names are declared in your res/values/attrs.xml of your current project or library project, namespace sidespinner will tell aapt to obtain attributes from your current project or library project.

Second, set custom attributes in your custom View like this:

<your-custom-view
     sidespinner:boolean-attr="true"
     sidespinner:integer-attr="5"
     sidespinner:enum-attr="none"//your enum values
     sidespinner:dimen-attr="10dp" />

I hope you are clear about this. If you want to know how to customize attributes, refer to @SteffenTimm's answer.




回答3:


change

xmlns:sidespinner="http://schemas.android.com/tools"

to

xmlns:sidespinner="http://schemas.android.com/apk/res-auto"

android studio will show custom attributes of your custom view.

be sure you defined custom attributes in res/values/attrs.xml



来源:https://stackoverflow.com/questions/31072453/does-android-studio-layout-editor-shows-custom-view-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!