如何保存按钮的样式并在以后检索它?

时间:2014-03-17 17:14:45

标签: java android android-layout

我需要存储当前样式的按钮,这样每当活动发送到后台或销毁并重新启动时,按钮会保留上次使用的样式。我知道如何保存和检索textviews的信息但我不知道如何为按钮样式执行此操作,基本上我对如何检索它更加困惑。 这是我设置按钮样式的代码:

case R.id.darkorange:
          for (Button currentButton : buttons) {
                currentButton.setBackgroundResource(R.drawable.darkorange);
            }

现在橙色可以是紫色,红色,蓝色或绿色。如何保存关于按钮的信息,并在以后重新创建活动时将其恢复。

1 个答案:

答案 0 :(得分:0)

这样做:

<强> RES /抽拉/ solid.xml:

 <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#0078a5"
        android:endColor="#00adee"
        android:angle="90"/>
    <padding android:left="15dp"
        android:top="1dp"
        android:right="15dp"
        android:bottom="1dp" />
    <stroke
        android:width="1dp"
        android:color="#0076a3" />
    <corners android:radius="8dp" />
</shape>

<强> activity_main.xml中:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<Button
    android:id="@+id/button1"
    style="@style/NiceButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:text="Colors"/>

   </LinearLayout>

<强> RES /值/ strings.xml中:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Buttons</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Color</string>

</resources>

<强> RES /值/ styles.xml:

<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>
 <style name="NiceButton" parent="@android:style/Widget.Button">
    <item name="android:gravity">center_vertical|center_horizontal</item>
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:background">@drawable/solid</item>
    <item name="android:textSize">16sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:focusable">true</item>
    <item name="android:clickable">true</item>
</style>
</resources>

<强>输出:

enter image description here