2014-09-15 3 views
0

현재 내 설정 클래스의 옵션으로 Android 애플리케이션에서 스위치를 사용하고 있습니다. 그러나 스위치의 상태를 false에서 true로 변경하고 메뉴로 돌아가서 설정 작업으로 돌아 가면 스위치의 상태가 기본값으로 돌아갑니다. 기본적으로 스위치의 상태를 저장하는 키 라인이있어 사용자가 스위치를 반환 할 때 상태가 동일하게 유지됩니까? 이 질문에 코드가 필요하다고 생각하지 않지만 도움이된다고 생각되면 알려 주시기 바랍니다. 첨부 해 드리겠습니다. 감사! 여기 Android 스위치 문제

<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="com.example.speedytext.Options" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

<Switch 
    android:id="@+id/switch1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/textView1" 
    android:layout_marginLeft="46dp" 
    android:layout_marginTop="48dp" 
    android:layout_toRightOf="@+id/textView1" 
    android:text="Switch" /> 

<Switch 
    android:id="@+id/switch2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignRight="@+id/switch1" 
    android:layout_below="@+id/switch1" 
    android:layout_marginTop="66dp" 
    android:text="Switch" /> 

</RelativeLayout> 

내 자바 코드 : onCreate()에서

import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.CompoundButton; 
import android.widget.CompoundButton.OnCheckedChangeListener; 
import android.widget.Switch; 

public class Options extends ActionBarActivity { 
private static Switch ding; 
private Switch countdown; 
public static boolean isDingChecked; 
public static boolean isCountdownChecked; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_options); 
    ding = (Switch) findViewById(R.id.switch1); 
    ding.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      // do something, the isChecked will be 
      // true if the switch is in the On position 
      isDingChecked = isChecked; 
      System.out.println(isDingChecked); 
      System.out.println(isDingChecked()); 
     } 
    }); 
    countdown = (Switch) findViewById(R.id.switch2); 
    countdown.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      // do something, the isChecked will be 
      // true if the switch is in the On position 
      isCountdownChecked = isChecked; 
      System.out.println(isCountDownChecked()); 
     } 
    }); 
    isDingChecked = ding.isChecked(); 
    isCountdownChecked= countdown.isChecked(); 

} 

public static boolean isDingChecked() 
{ 
    return isDingChecked; 
} 

public static boolean isCountDownChecked() 
{ 
    return isCountdownChecked; 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.options, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 
} 
+0

일부 코드는 정말 도움이됩니다! – EightBitBoy

+0

첨부! 감사! – user2677095

+0

예, 일부 코드가 있습니다. 일반적으로 스위치 또는 switchPreference를 사용하고 있습니까? switchPreference만이 상태를 유지할 것이고, 일반적인 스위치는 그렇지 않습니다. – Opiatefuchs

답변

0

, 저장된와 setChecked()를 호출 값이었다 무엇에 기본 설정 "체크"여기

내 활동 코드 이전에 저장되었습니다.

또한 설정을 예 : 공유 환경 설정. static 변수는 응용 프로그램 다시 시작시 지속되지 않으며 종종 코드를 유지 관리하기가 더 어렵습니다. 활동 공유 환경의

+0

그래, 왜 제가 상식에 대해 생각하지 않았는지 전혀 모르겠습니다. 감사! – user2677095

+0

그다지 간단하지 않았습니다 ... 어쨌든 감사드립니다. – user2677095

+0

그래서 지금 무슨 문제가 있습니까? – laalto

0

공유 환경 설정 클래스

public class AppPreferences { 

    private SharedPreferences appSharedPrefs; 
    private Editor prefsEditor; 

    public AppPreferences(Context context, String Preferncename) { 
     this.appSharedPrefs = context.getSharedPreferences(Preferncename, 
       Activity.MODE_PRIVATE); 
     this.prefsEditor = appSharedPrefs.edit(); 
    } 

    /**** 
    * 
    * getdata() get the value from the preference 
    * 
    * */ 
    public String getData(String key) { 
     return appSharedPrefs.getString(key, ""); 
    } 

    /**** 
    * 
    * SaveData() save the value to the preference 
    * 
    * */ 
    public void SaveData(String text, String Tag) { 
     prefsEditor.putString(Tag, text); 
     prefsEditor.commit(); 

    } 


    public void clear() 
    { 

     prefsEditor.clear(); 
     prefsEditor.commit(); 
    } 

} 

사용

AppPreferences appPref; 

appPref = new AppPreferences(getApplicationContext(), "PREFS"); 

스위치의 상태가 참 또는 거짓 상태를 저장 변경되면 상태

을 저장하려면 공유 환경 설정의 태그

이 줄을 사용하여

appPref.SaveData("Value", "Tag"); 

상태

은 그래서

appPref.getData("state"); 
if(appPref.getData("state").equals("true")) 
{ 
//set ur switch button to checked state 
} 
else if(appPref.getData("state").equals("false")) 
{ 
//set ur switch button to unchecked state 
} 
를 사용하여 공유 선호 에서 값을 가져 활동의 한 OnCreate 체크 상태에 대한 다음과 같은 체크되지 않은 상태

에 대한 appPref.SaveData("true", "state");

appPref.SaveData("false", "state"); 될 것입니다

그런 다음 결과 문자열에서 true 또는 false를 확인하십시오. 및 t 그는 그에 따라 적절하게 전환합니다

+0

appPref.getData ("state")가 true 또는 false를 나타내는 부울 또는 문자열을 반환해야합니까? – user2677095

+0

문자열은 반환 형식이 될 것입니다. y 결과 문자열을 equals 메서드와 비교했습니다. –

+0

오, 제 사과는 페이지를 새로 고치지 않아서 편집을 보지 못했습니다. 그것이 효과가 있는지 보도록하겠습니다! – user2677095