2014-10-28 4 views
0

그래서이 문제는 내 ListPreference가 두 번 클릭하여 실제로 onClick 수신기에있는 작업을 수행하는 경우에 발생합니다. 여기 내 코드가ListPreference onClickListener가 두 번 실행됩니다.

@Override 
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { 
    final ListPreference prefListThemes = (ListPreference) findPreference("prefMaterialThemes"); 
    prefListThemes.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { 
     @Override 
     public boolean onPreferenceClick(Preference preference) { 
      Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show(); 
      System.out.println("Test prntln"); 
      // Restart Activity to apply Theme 
      Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK); 
      startActivity(intent); 
      return false; 
     } 
    }); 

내가 뭘 하려는지 알 수 있듯이 내 테마를 적용하기 위해 앱을 다시 시작하는 것만 알면된다. 처음에는 그 문제를 일으키는 의도 코드일지도 모른다고 생각했지만, onclick 리스너에서 축사 만해도 목록 환경 설정을 클릭하고 옵션을 선택한 다음 환경 설정을 다시 클릭하고 옵션을 한 번 선택해야합니다 실제로 무엇이든 할 수있는 더 많은 것. 그게 도움이된다면 도움이 될거야. 고맙습니다! preferences.xml로에서

import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.graphics.Color; 
import android.os.Bundle; 
import android.preference.CheckBoxPreference; 
import android.preference.EditTextPreference; 
import android.preference.ListPreference; 
import android.preference.Preference; 
import android.preference.PreferenceActivity; 
import android.preference.PreferenceManager; 
import android.support.v4.content.IntentCompat; 
import android.widget.Toast; 

import com.iliakplv.notes.R; 
import com.iliakplv.notes.gui.main.LauncherActivity; 
import com.iliakplv.notes.gui.main.MainActivity; 

import java.util.List; 

public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { 

    private static final int PREFERENCES = R.xml.preferences; 

    private final static String PREFS_LIST_OF_THEMES = "prefMaterialThemes"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     //noinspection deprecation 
     addPreferencesFromResource(PREFERENCES); 
     PreferenceManager.setDefaultValues(this, PREFERENCES, false); 

     // These 3 lines are required for the onSharedPreferenceChanged method 
     Context context = getApplicationContext(); 
     SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); 
     settings.registerOnSharedPreferenceChangeListener(this); 
     // End 
    } 

    @Override 
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { 

     final CheckBoxPreference prefDarkThemeCB = (CheckBoxPreference) findPreference("prefDarkTheme"); 
     prefDarkThemeCB.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { 
      @Override 
      public boolean onPreferenceClick(Preference preference) { 
       if (prefDarkThemeCB.isChecked()) { 
        // Restart Activity to apply Theme 
        Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK); 
        startActivity(intent); 
       } else if (prefDarkThemeCB.isChecked() == false) { 
        // Also restart activity to apply default theme 
        Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK); 
        startActivity(intent); 
       } 
       return false; 
      } 
     }); 

     final ListPreference prefListThemes = (ListPreference) findPreference("prefMaterialThemes"); 
     prefListThemes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { 
      public boolean onPreferenceChange(Preference preference, Object newValue) { 
       Toast.makeText(getApplicationContext(), "toast", Toast.LENGTH_SHORT).show(); 
       System.out.println("Toasted"); 
       // Restart Activity to apply Theme 
       Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
       intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK); 
       startActivity(intent); 
       return false; 
      } 
     }); 

     final CheckBoxPreference prefRequirePasswordCB = (CheckBoxPreference) findPreference("prefEnablePasswordLock"); 
     prefRequirePasswordCB.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { 
      @Override 
      public boolean onPreferenceClick(Preference preference) { 
       if (prefRequirePasswordCB.isChecked()) { 
        EditTextPreference prefUsersPass = (EditTextPreference) findPreference("prefPassword"); 
        // Check to see if the users password is empty before allowing them to check the require password box 
        if (prefUsersPass.getText().toString().isEmpty()) { 
         prefRequirePasswordCB.setChecked(false); 
         Toast.makeText(getApplicationContext(), R.string.password_required, Toast.LENGTH_SHORT).show(); 
         //System.out.println("Empty password"); 
        } else if (prefUsersPass.getText().toString().trim().length() == 0) { 
         // The above line checks to see if the User's pass is all spaces :p 
         prefRequirePasswordCB.setChecked(false); 
         Toast.makeText(getApplicationContext(), R.string.password_required, Toast.LENGTH_SHORT).show(); 
         //System.out.println("Trimmed the password because they used all spaces probably and still empty"); 
        } else { 
         Toast.makeText(getApplicationContext(), R.string.password_has_been_set, Toast.LENGTH_SHORT).show(); 
         //System.out.println("kapow! they have a password and its: " + prefUsersPass.getText().toString()); 
        } 
       } 
       return false; 
      } 
     }); 

    } 

} 

preferences.xml로 (목록의 기본 설정에 대한 항목을 얻을 수있는 preference.xml 파일에 사용)

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

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 

    <PreferenceCategory android:title="@string/security_pref_category"> 
     <CheckBoxPreference 
      android:defaultValue="false" 
      android:key="prefEnablePasswordLock" 
      android:summary="@string/pref_require_password_for_app_description" 
      android:title="@string/pref_require_password_for_app" /> 
     <EditTextPreference 
      android:defaultValue="" 
      android:key="prefPassword" 
      android:summary="@string/pref_password_description" 
      android:title="@string/pref_password_title" /> 
    </PreferenceCategory> 


    <PreferenceCategory android:title="@string/look_and_feel_pref_category"> 
     <CheckBoxPreference 
      android:defaultValue="false" 
      android:key="prefDarkTheme" 
      android:summary="@string/pref_dark_theme_description" 
      android:title="@string/pref_dark_theme" /> 

     <ListPreference 
      android:defaultValue="1" 
      android:entries="@array/pref_app_themes" 
      android:entryValues="@array/pref_app_theme_values" 
      android:key="prefMaterialThemes" 
      android:summary="@string/pref_change_theme_description" 
      android:title="@string/pref_change_theme" /> 


    </PreferenceCategory> 

    <PreferenceCategory android:title="@string/misc_pref_category"> 
     <CheckBoxPreference 
      android:defaultValue="true" 
      android:key="linkify_note_text" 
      android:summary="@string/settings_linkify_subtitle" 
      android:title="@string/settings_linkify_title" /> 

     <Preference 
      android:key="contactDevKey" 
      android:summary="@string/pref_contact_developer_description" 
      android:title="@string/pref_contact_developer"> 
      <intent 
       android:action="android.intent.action.VIEW" 
       android:data="mailto:[email protected]?subject=Support *Notes"> 
       <extra 
        android:name="android.intent.extra.TEXT" 
        android:value="" /> 
       <!-- Value is whats in the body, blank for now --> 
      </intent> 
     </Preference> 

    </PreferenceCategory> 


</PreferenceScreen> 

Arrays.xml을 환경 설정을 얻을 수

SettingsActivity

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


    <string-array name="pref_app_themes"> 
     <item name="1">Default</item> 
     <item name="2">Dark</item> 
     <item name="3">AMOLED</item> 
     <item name="4">Red</item> 
     <item name="5">Pink</item> 
     <item name="6">Purple</item> 
     <item name="7">Deep Purple</item> 
     <item name="8">Blue</item> 
     <item name="9">Light Blue</item> 
     <item name="10">Cyan</item> 
     <item name="11">Teal</item> 
     <item name="12">Green</item> 
     <item name="13">Light Green</item> 
     <item name="14">Lime</item> 
     <item name="15">Yellow</item> 
     <item name="16">Amber</item> 
     <item name="17">Orange</item> 
     <item name="18">Deep Orange</item> 
     <item name="19">Brown</item> 
     <item name="20">Grey</item> 
     <item name="21">Blue Grey</item> 

    </string-array> 
    <string-array name="pref_app_theme_values"> 
     <item name="1">1</item> 
     <item name="2">2</item> 
     <item name="3">3</item> 
     <item name="4">4</item> 
     <item name="5">5</item> 
     <item name="6">6</item> 
     <item name="7">7</item> 
     <item name="8">8</item> 
     <item name="9">9</item> 
     <item name="10">10</item> 
     <item name="11">11</item> 
     <item name="12">12</item> 
     <item name="13">13</item> 
     <item name="14">14</item> 
     <item name="15">15</item> 
     <item name="16">16</item> 
     <item name="17">17</item> 
     <item name="18">18</item> 
     <item name="19">19</item> 
     <item name="20">20</item> 
     <item name="21">21</item> 
    </string-array> 

</resources> 

답변

2

onSharedPreferenceChanged는 환경 설정이 일단 변경되면 호출됩니다. ged. 그런 일이 발생하면 값을 다시 변경하면 트리거되는 OnPreferenceClickListener를 설정합니다. 이것이 테마 값을 두 번 변경하는 경우에만 코드가 실행되는 이유입니다. 대신에서 onCreate에

넣어이 :

final ListPreference prefListThemes = (ListPreference) findPreference("prefMaterialThemes"); 
prefListThemes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { 
    public boolean onPreferenceChange(Preference preference, Object newValue) { 
     Toast.makeText(getApplicationContext(), "toast", Toast.LENGTH_SHORT).show(); 
     System.out.println("Toasted"); 
     // Restart Activity to apply Theme 
     Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK); 
     startActivity(intent); 

     return true; 
    } 
}); 
+0

나는 그것을 또한 시도했다. 그것은 똑같은 일을합니다. 작동시키기 위해서 두 번 항목을 선택해야합니다. – Fernando

+0

아니야. 나는 이것을 gazillion 번 사용했고 작동한다. –

+0

전에도 사용해 본 것처럼 당신을 믿습니다. 그러나 이것이 처음으로 일어났습니다. 다른 모든 환경 설정은 어떤 이유로 든이 설정을 제외하고는 정상적으로 작동합니다. 코드의 모든 부분을 파헤 치면 아무 것도 찾아 내지 못합니다. – Fernando