2017-09-23 50 views
0

我试图根据android.widget.Button创建自己的按钮。但是,当我设置样式属性编程,我得到这个渲染问题:以编程方式设置样式属性时,无法在当前主题中找到样式“My_Button”

无法找到风格“My_Button”在当前主题

在XML设定。但是风格是工作。

Screenshot

我这么想吗?

P/s:英语不是我的母语,请原谅我的错误。


activity_main.xml中

<com.myapp.Components.Button 
    android:id="@+id/xx" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:onClick="touch_" 
    app:_icon=""/> 
<com.myapp.Components.Button 
    style="@style/My_Button" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:onClick="touch" 
    app:_icon=""/> 

Button.java

public class Button extends android.widget.Button { 
    public Button(@NonNull Context context) { 
     super(context, null, R.style.My_Button); 
     init(context, null); 
    } 

    public Button(@NonNull Context context, @Nullable AttributeSet attrs) { 
     super(context, attrs, R.style.My_Button); 
     init(context, attrs); 
    } 
    public Button(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { 
     super(context, attrs, R.style.My_Button); 
     init(context, attrs); 
    } 
    // ... more 
} 

styles.xml

<style name="My_Button" parent="Base.Widget.AppCompat.Button.Borderless"> 
    <item name="android:foreground">?android:attr/selectableItemBackground</item> 
    <item name="android:background">#592612</item> 
    <item name="android:gravity">center</item> 
</style> 

回答

0

最后,我找到了答案!

替换:

super(context, attrs, R.style.My_Button);super(context, attrs, R.attr.ButtonStyle);

styles.xml添加

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> 
    <item name="ButtonStyle">@style/Button_Style</item> 
    ... 
</style> 

attrs.xml添加

<declare-styleable name="Theme"> 
    <attr name="ButtonStyle" format="reference"/> 
</declare-styleable> 
相关问题