android - 使用自定义属性创建默认样式

标签 android styles themes attr

所以这是我的问题:我创建了一个自定义组件,它扩展了 Button 这个按钮有一个名为 testAttr 的属性。

<declare-styleable name="TestButton" parent="@android:style/Widget.Button">
    <attr name="testAttr" format="reference|color"/>
</declare-styleable>

我想为这个组件创建一个默认样式,所以我添加了这个:

<declare-styleable name="TestTheme">
    <attr name="testStyle" format="reference"/>
</declare-styleable>

<style name="Theme.AppTheme" parent="@android:style/Theme" >
    <item name="testStyle">@style/test</item>
</style>

问题是我想像这样同时使用 android 属性和我自己的属性,这是行不通的:

<style name="test" parent="@android:style/Widget.Button">
    <item name="android:background">#FF0000</item>
    <item name="testAttr">testText</item>
</style>

我在自定义组件中设置默认样式如下:

public myButton(final Context context) {
    this(context, null);
}

public myButton(final Context context, final AttributeSet attrs) {
    this(context, attrs, R.styleable.TestTheme_testStyle);
}

public myButton(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);

    final TypedArray array = context.obtainStyledAttributes(
            attrs,
            R.styleable.TestButton,
            defStyle,
            R.style.testDefault);
        final String s = array.getString(R.styleable.TestButton_testAttr);
        setText(s);
        array.recycle();
}

当然,我在 list 中设置了主题:

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppTheme" >

    <activity
        android:name=".TestActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


</application>

由于某种原因它总是退回到默认样式并且从不设置 android 属性。那么我在这里遗漏了什么吗?

最佳答案

好吧,我应该在问问题之前看起来更好......

找到解决方案:

替换为:

public myButton(final Context context, final AttributeSet attrs) {
    this(context, attrs, R.styleable.TestTheme_testStyle);
}

用这个:

public myButton(final Context context, final AttributeSet attrs) {
    this(context, attrs, R.attr.testStyle);
}

关于android - 使用自定义属性创建默认样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12072153/

相关文章:

javascript - 添加 "progid:DXImageTransform.Microsoft"使文本模糊

Python Tkinter。无法为程序的第二个窗口应用主题

linux - 这是哪个主题或桌面环境?

android - 如何删除使用 Uri 创建的文件?

php - Android 中的 FIrebase 401 未授权错误 FCM

android - ACTION_IMAGE_CAPTURE 将图像文件返回为 Extra 而不是 Data

wpf - 如何使 System.Windows.MessageBox 按钮样式化?

Javascript,使用 if 语句更改单击元素的颜色

html - 基本 CSS 帮助 - 删除形状

android - Appcelerator、PhoneGap 或 JAVA