如何在Android中定义自定义属性

如何在Android中定义自定义属性,android,android-xml,Android,Android Xml,我想在我的Android应用程序中定义一个自定义属性 我已经定义了GifMovieView类,它扩展了View 所有3个构造函数都调用init(AttributeSet attrs)方法: 我抛出一个异常,因为mUrl为null 此属性在mainActivity_layout.xml中定义如下: <com.example.propertyproject.GifMovieView android:id="@+id/my_id" android:layout_width="w

我想在我的Android应用程序中定义一个自定义属性

我已经定义了GifMovieView类,它扩展了View

所有3个构造函数都调用init(AttributeSet attrs)方法:

我抛出一个异常,因为mUrl为null

此属性在mainActivity_layout.xml中定义如下:

 <com.example.propertyproject.GifMovieView
    android:id="@+id/my_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    gif:url="http://mygif.com/mygif.gif" />

url总是空的

包裹名称有误吗?是否必须更改packageName

事先


Adriano.

*\u layout.xml
用于定义GUI的布局,而不是定义自定义字符串

还有一个地方是为它保留的,它在
res/values/strings.xml
中。如果
strings.xml
不存在,请使用以下内容创建它:

<?xml version="1.0" encoding="utf-8"?>
<resources>    
  <string name="gif_url">http://mygif.com/mygif.gif</string>
</resources>
  • 在values文件夹中创建attrs.xml文件,它包含所有自定义属性
  • <?xml version="1.0" encoding="utf-8"?>
    
    <resources>
        <declare-styleable name="MyTextView">
            <attr name="font_name" format="string" />
        </declare-styleable>
    </resources>
    
    <style name="Header_Text_Text1">
            <item name="android:textColor">@color/text1_header_text</item>
            <item name="android:textSize">26px</item>
            <item name="android:textStyle">bold</item>
            <item name="android:padding">2dp</item>
            <item name="[YOUR PACKAGE NAME]:font_name">calibri</item>
        </style>
    
    <YOUR PACKAGE NAME.MyTextView
            android:id="@+id/header_txtTitle"
            style="@style/Header_Text_Text1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/header_home"
            android:layout_marginTop="2dp"
            android:text="" />
    
    }

  • 新我们可以在布局中使用名为“MyTextview”的新文本视图
  • <?xml version="1.0" encoding="utf-8"?>
    
    <resources>
        <declare-styleable name="MyTextView">
            <attr name="font_name" format="string" />
        </declare-styleable>
    </resources>
    
    <style name="Header_Text_Text1">
            <item name="android:textColor">@color/text1_header_text</item>
            <item name="android:textSize">26px</item>
            <item name="android:textStyle">bold</item>
            <item name="android:padding">2dp</item>
            <item name="[YOUR PACKAGE NAME]:font_name">calibri</item>
        </style>
    
    <YOUR PACKAGE NAME.MyTextView
            android:id="@+id/header_txtTitle"
            style="@style/Header_Text_Text1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/header_home"
            android:layout_marginTop="2dp"
            android:text="" />
    
    
    

    我不想定义字符串:我只想为扩展视图对象的实例定义自定义属性。例如,我可以用布尔值或int值定义属性。但我不知道如何进入这片土地。