简体   繁体   English

如何在重新启动,按回并更改方向后保留android app imageButton的onClick状态

[英]How to retain an android app imageButton's onClick state after restarting, pressing back and changinging orientation

I am making an app that control light bulb remotely. 我正在制作一个可以远程控制灯泡的应用程序。 so i require that app saves automatically the previous state(variables, onlick button, etc) and resume it after i restart the app. 因此,我要求该应用自动保存以前的状态(变量,onlick按钮等),并在我重新启动该应用后恢复它。 For example if i pressed on bulb(in my code it changes picture on click) and picture changes so when i close app and reopen it, the image shown should be changed one. 例如,如果我按下灯泡(在我的代码中,它会在单击时更改图片)并且图片也会更改,因此当我关闭应用程序并重新打开它时,显示的图像应该更改为一张。

Here's my code 这是我的代码

package room.bt4u.com.roomcontrol;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
public class MainActivity extends AppCompatActivity {
ImageButton ib;
MediaPlayer toggleSound;
ImageButton aButton,aButton2;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toggleSound=MediaPlayer.create(this, R.raw.z);
    aButton = (ImageButton) findViewById(R.id.imageButton);
    aButton2 = (ImageButton) findViewById(R.id.imageButton2);
    SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
    Boolean c = sharedPreferences.getBoolean("clicked", false);
    Boolean d = sharedPreferences.getBoolean("clicked2",false);

    if(c) {
        aButton.setImageResource(R.drawable.on);
    }
    else {
        aButton.setImageResource(R.drawable.off);

    }
    if(d){

        aButton2.setImageResource(R.drawable.on);
    }
    else {

        aButton2.setImageResource(R.drawable.off);
    }
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}


public void buttonClick(View v) {
    SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
    Boolean c = sharedPreferences.getBoolean("clicked",false);
    if (!c) {
        aButton.setImageResource(R.drawable.on);
        toggleSound.start();
        sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("clicked", true);
        editor.commit();
    }
    if(c){
        aButton.setImageResource(R.drawable.off);
        sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor = sharedPreferences.edit();
        editor.putBoolean("clicked", false);
        editor.commit();
        toggleSound.start();

    }
}
public void buttonClick2(View v) {
    SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
    Boolean d = sharedPreferences.getBoolean("clicked",false);
    if (!d) {
        aButton2.setImageResource(R.drawable.on);
        toggleSound.start();
        sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("clicked2", true);
        editor.commit();
    }
    if(d){
        aButton2.setImageResource(R.drawable.off);
        sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor = sharedPreferences.edit();
        editor.putBoolean("clicked2", false);
        editor.commit();
        toggleSound.start();

    }
}

And here's the XML FILE 这是XML FILE

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
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="room.bt4u.com.roomcontrol.MainActivity"
android:orientation="vertical">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ROOM NO. 1046"
    android:textSize="45sp"
    android:textStyle="bold"
    android:layout_centerHorizontal="true"
    android:textColor="#0786e7"
    android:id="@+id/textView"
    android:includeFontPadding="false"
   android:gravity="center_horizontal"
    />


<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageButton"
    android:layout_below="@+id/textView"
    android:src="@drawable/off"
    android:layout_marginTop="35dp"
    android:layout_alignParentLeft="true"
    android:background="#01FFFFFF"
    android:onClick="buttonClick"/>

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageButton2"
    android:layout_alignTop="@+id/imageButton"
    android:layout_below="@+id/textView"
    android:src="@drawable/off"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:background="#01FFFFFF"
    android:onClick="buttonClick2"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Swarnveer&apos;s"
    android:id="@+id/textView2"
    android:layout_below="@+id/imageButton"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginLeft="20dp"
    android:textStyle="bold"
    android:textColor="#f20606"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Sajal&apos;s"
    android:id="@+id/textView3"

    android:layout_below="@+id/imageButton2"
    android:layout_alignRight="@+id/imageButton2"
    android:layout_alignEnd="@+id/imageButton2"
    android:layout_marginRight="35dp"
    android:layout_marginEnd="35dp"
    android:textStyle="bold"
    android:textColor="#f20606"/>

</RelativeLayout>

You can use SharedPreferences: 您可以使用SharedPreferences:

referring here for the infos: You can use SharedPreferences to save little setting datas on your phone. 请参阅此处以获取相关信息:您可以使用SharedPreferences在手机上保存少量设置数据。

In your onPause() , use the following code: onPause() ,使用以下代码:

SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
prefs.edit().putString("myKey", "myColorState").apply();

In this way the setting of "myColorState" is saved under the key "myKey". 这样,“ myColorState”的设置将保存在键“ myKey”下。

In onResume() you can retrieve this value using onResume()您可以使用

SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
String myColor = prefs.getString("myKey", "defaultValue"); 

In this way you have your datas and you can use them in the activity 这样,您就可以拥有数据,并可以在活动中使用它们

If you don't have bidirectional communication with the Bulb, saving the states to SharedPreferences seems like the best way to go. 如果您与灯泡之间没有双向通信,则将状态保存到SharedPreferences似乎是最好的方法。

You can retrieve the data from the SharedPreferences in your Activity or Fragment lifecycle Methods ( onConfigurationChanged() , onResume() , onStart() ). 您可以在ActivityFragment生命周期方法( onConfigurationChanged()onResume()onStart() )中从SharedPreferences中检索数据。

Check out SharedPreferences here 在此处查看SharedPreferences

您可以使用SharedPref通过更改屏幕方向或按Backpress上的任何键来保存数据,也可以使用此键再次获取该数据。

    Try this:


        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            toggleSound= MediaPlayer.create(this, R.raw.z);
            SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
            Boolean c = sharedPreferences.getBoolean("clicked");
            if(c){
                aButton.setImageResource(R.drawable.on);
            }
            else {
                aButton.setImageResource(R.drawable.off);
            }        
        }


        public void buttonClick(View v) {
            switch (choose){
                case 1:ImageButton aButton = (ImageButton) v;
                    aButton.setImageResource(R.drawable.on);
                    toggleSound.start();
                    choose++;
                    SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean("clicked", true);
                    editor.commit();
                    break;
                case 2:ImageButton bButton = (ImageButton) v;
                    bButton.setImageResource(R.drawable.off);
SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean("clicked", false);
                    editor.commit();
                    toggleSound.start();
                    choose--;
                    break;
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在浏览器中按回后如何保留下拉列表及其选择 - How to retain the dropdown and their selection after pressing back in browser 如何在Java / Android Studio中使Imagebutton更改Image onClick in,并在ClickOut上返回其原始图像 - How to make an Imagebutton change Image onClick in and Back to its original on ClickOut in Java/Android Studio 如何检查应用程序的方向是否在android上固定 - how to check if app's orientation is fixed on android Android:如何在后退按钮操作栏和设备的后退按钮上保留对象的状态 - Android: How can I retain the state of an object on back button Action bar and back button of device 按下时如何保存图像按钮的状态? - How to save imagebutton's state when pressed? 按下操作栏上的“后退”,Android应用程序崩溃 - Android app crashes on pressing “back” on action bar 如何从android中的另一个应用程序定义应用程序的屏幕方向? - How to define an app's screen orientation from another app in android? 从 backstack 获取片段后按回崩溃应用程序,“Android IllegalStateException Fragment already added” - Pressing back after getting fragment from backstack crashes app, “Android IllegalStateException Fragment already added” 在子活动中按下返回按钮后,Android主要活动的元素不响应 - Android main activity's elements do not respond after pressing the back button from child activity 通过按返回按钮重新启动上一个活动 - Restarting the previous activity by pressing back button
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM