Извините, ничего не найдено.

Не расстраивайся! Лучше выпей чайку!
Регистрация
Справка
Календарь

Вернуться   forum.boolean.name > Программирование игр для мобильных телефонов > Android

Android Разработка игр на платформе Android

Ответ
 
Опции темы
Старый 11.05.2016, 00:18   #1
burovalex
Разработчик
 
Аватар для burovalex
 
Регистрация: 04.04.2012
Сообщений: 468
Написано 37 полезных сообщений
(для 60 пользователей)
Стили кнопок..

Ребят, выручайте, уже неделю по вечерам читаю, тестиру нифига не работает, помогите!!
Хочу сделать возможность смены темы в приложении, со сменой темы пытаюсь поменять цвет кнопок и тут у меня полный ступор, и не догоняю в чем проблема.

Лаунчер-активити основан на AppCompatActivity

Вот описаны мои стили:

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary_purple</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark_purple</item>
        <item name="colorAccent">@color/colorAccent_purple</item>

        <item name="android:buttonStyle">@style/ButtonPurple</item>
    </style>

    <style name="purpleTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary_purple</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark_purple</item>
        <item name="colorAccent">@color/colorAccent_purple</item>

        <item name="android:buttonStyle">@style/ButtonGreen</item>
    </style>

    <style name="theme3" parent="Base.Theme.AppCompat.Light">
        <item name="colorPrimary">@android:color/holo_red_dark</item>
        <item name="colorPrimaryDark">#660b0b</item>
        <item name="colorAccent">#f27e19</item>

    </style>


    <style name="ButtonPurple" parent="Base.Widget.AppCompat.Button">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">?android:attr/textColorPrimary</item>
        <item name="android:background">@drawable/button_shape_purple</item>
    </style>

    <style name="ButtonGreen" parent="Base.Widget.AppCompat.Button">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">?android:attr/textColorPrimary</item>
        <item name="android:background">@drawable/button_shape_green</item>
    </style>
</resources>


ВОт так выглядят шейпы на кнопки:

Файл button_shape_green.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- NORMAL STATE -->
<item>
<shape>
<solid
android:color="#689f38"/>
<corners
android:radius="@dimen/buttonCornerRadius"/>
<padding
android:bottom="@dimen/buttonPadding"
android:left="@dimen/buttonPadding"
android:right="@dimen/buttonPadding"
android:top="@dimen/buttonPadding"/>
</shape>
</item>
</selector>


Файл button_shape_purple.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid
android:color="#cb65d7"/>
<corners
android:radius="@dimen/buttonCornerRadius"/>
<padding
android:bottom="@dimen/buttonPadding"
android:left="@dimen/buttonPadding"
android:right="@dimen/buttonPadding"
android:top="@dimen/buttonPadding"/>
</shape>
</item>
</selector>


Вот мой layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:fbutton="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="ru.avb.iremember.UITestActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="theme1"
android:id="@+id/button_theme1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="theme2"
android:id="@+id/button_theme2"
android:layout_below="@+id/button_theme1"
android:layout_alignLeft="@+id/button_theme1"
android:layout_alignStart="@+id/button_theme1"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="theme3"
android:id="@+id/button_theme3"
android:layout_below="@+id/button_theme2"
android:layout_alignLeft="@+id/button_theme2"
android:layout_alignStart="@+id/button_theme2" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView4"
android:layout_below="@+id/button_theme3"
android:layout_alignLeft="@+id/button_theme3"
android:layout_alignStart="@+id/button_theme3"
android:theme="@style/Caption"
android:text="Caption" />

<android.support.v7.widget.AppCompatButton
android:text="New Button"
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView9"
android:layout_alignLeft="@+id/textView7"
android:layout_alignStart="@+id/textView7"
android:theme="@style/B1" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView5"
android:theme="@style/Hint"
android:focusable="true"
android:elegantTextHeight="false"
android:ellipsize="end"
android:text="Hint"
android:layout_below="@+id/textView4"
android:layout_alignRight="@+id/button_theme3"
android:layout_alignEnd="@+id/button_theme3" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView6"
android:theme="@style/Body0"
android:focusable="true"
android:elegantTextHeight="false"
android:ellipsize="end"
android:text="Body0"
android:layout_below="@+id/textView5"
android:layout_toRightOf="@+id/button3"
android:layout_toEndOf="@+id/button3" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView7"
android:theme="@style/Body1"
android:focusable="true"
android:elegantTextHeight="false"
android:ellipsize="end"
android:text="Body1"
android:layout_below="@+id/textView6"
android:layout_alignLeft="@+id/textView4"
android:layout_alignStart="@+id/textView4" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView8"
android:theme="@style/Body2"
android:focusable="true"
android:elegantTextHeight="false"
android:ellipsize="end"
android:text="Body2"
android:layout_below="@+id/textView7"
android:layout_alignRight="@+id/textView5"
android:layout_alignEnd="@+id/textView5" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView9"
android:theme="@style/Body2"
android:focusable="false"
android:elegantTextHeight="false"
android:ellipsize="end"
android:text="Body2"
android:layout_below="@+id/textView8"
android:layout_alignLeft="@+id/textView6"
android:layout_alignStart="@+id/textView6"
android:editable="false"
android:enabled="false" />

<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button4"
android:layout_below="@+id/button3"
android:layout_centerHorizontal="true"
android:layout_marginTop="2dp"
android:padding="12dp"
android:layout_margin="2dp"
android:theme="@style/B2" />

<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button5"
android:layout_below="@+id/button4"
android:layout_alignRight="@+id/button4"
android:layout_alignEnd="@+id/button4"
style="@style/ButtonPurple" />
<!--
android:shadowColor="#3ee121"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="30"
-->


</RelativeLayout>


При смене темы - меняются цвета TitleBar'a, Текстов, Надписей на кнопках, а сми кнопки как были серыми так и остались...
__________________
(Offline)
 
Ответить с цитированием
Старый 11.05.2016, 00:22   #2
burovalex
Разработчик
 
Аватар для burovalex
 
Регистрация: 04.04.2012
Сообщений: 468
Написано 37 полезных сообщений
(для 60 пользователей)
Ответ: Стили кнопок..

Заметил что при смене у Активити "extends AppCompatActivity" на просто "extends Activity" у кнопок цвета начинают меняться, но смотрится старовато и многие сис. аттрибуты не работают типа PrimaryColor и т.д.
__________________
(Offline)
 
Ответить с цитированием
Старый 11.05.2016, 06:51   #3
Жека
Дэвелопер
 
Регистрация: 04.09.2005
Адрес: Красноярск
Сообщений: 1,376
Написано 491 полезных сообщений
(для 886 пользователей)
Ответ: Стили кнопок..

Вот тут ребята говорят, что если тема была установлена после вызова super.onCreate у активити, то нужно либо перезапустить активити, либо вызвать метод recreate() после setTheme().
И предупреждают, что если у тебя несколько активити, то для получения эффекта нужно перезапустить их все.
(Offline)
 
Ответить с цитированием
Сообщение было полезно следующим пользователям:
St_AnGer (11.05.2016)
Старый 11.05.2016, 12:20   #4
burovalex
Разработчик
 
Аватар для burovalex
 
Регистрация: 04.04.2012
Сообщений: 468
Написано 37 полезных сообщений
(для 60 пользователей)
Ответ: Стили кнопок..

Я так и делаю, пересоздаю активити после смены темы.
Я ж говорю, у меня цвет текста меняется, т.е. тема работает. Но сами кнопки не хотят менять стиль.
Я походу неправильного парента в стиле выбираю или нетуда присваиваю. Хотя сколько примеров находил также писали:
<item name="android:buttonStyle">@style/MyButtonStyle</item>

Может у кого-нибудь пример есть со стилями кнопок AppCompat?
__________________
(Offline)
 
Ответить с цитированием
Старый 12.05.2016, 08:20   #5
Жека
Дэвелопер
 
Регистрация: 04.09.2005
Адрес: Красноярск
Сообщений: 1,376
Написано 491 полезных сообщений
(для 886 пользователей)
Ответ: Стили кнопок..

Я нашёл ответ: проблема в атрибуте android:buttonStyle.
- When should I use android: attribute name?
- From appcompat v21+ you should drop them.
Т.е. нужно писать просто buttonStyle.
(Offline)
 
Ответить с цитированием
Старый 12.05.2016, 14:16   #6
burovalex
Разработчик
 
Аватар для burovalex
 
Регистрация: 04.04.2012
Сообщений: 468
Написано 37 полезных сообщений
(для 60 пользователей)
Ответ: Стили кнопок..

Спасибо Женя!
Разобрался кое-как, нашел случайно простой ответ на стеке
Просто надо было использовать не аттрибут style, а аттрибут theme

<Button
    ......
    android:theme="@style/MyButtonTheme"
    ......
    />
<style name="MyButtonTheme" parent="Widget.AppCompat.Button">
    <item name="colorButtonNormal">@color/my_color</item>
</style>
Так же для изменения цвета работает <item name="backgroundTint">

Да и вообще принцип понятен стал:
Если выбираешь аттрибут, недоступный на твоем API, например android:backgroundTint. ИДЕ ругается на тебя что этот аттрибут доступен с 21+ API - просто стираем "android:" получаем "backgoundTint".
IDE теперь ругаться не будет и отработает AppCompat и будет счастие.

А еще я теперь понял что надо работать либо Только со стилями, либо Только с темами, а иначе перемешаете все и будете долго и упорно гуглить как я )
__________________
(Offline)
 
Ответить с цитированием
Ответ


Опции темы

Ваши права в разделе
Вы не можете создавать темы
Вы не можете отвечать на сообщения
Вы не можете прикреплять файлы
Вы не можете редактировать сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.


Часовой пояс GMT +4, время: 08:36.


vBulletin® Version 3.6.5.
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Перевод: zCarot
Style crйe par Allan - vBulletin-Ressources.com