0

ListPreference에 3 개의 옵션이있는 PreferenceActivity이 있습니다. 내 MainActivity's xml-file (activity_main.xml)에서이 ListPreference에 선택된 Button의 표시 여부를 VISIBLE으로 설정했습니다.Android - SharedPreference 두 번째 시간 이후에만 MainActivity 공개 설정이 변경됨

하나의 작은 문제를 제외하고 모든 것이 작동합니다. 두 번째 설정 화면에서 ListPreference을 변경 한 후에 만 ​​주 화면에서 변경됩니다.

은 더 명확하게하려면 :

응용 프로그램이 시작
  1. MainActivity'sactivity_main.xml 마지막으로 저장된 환경 설정 버튼 VISIBLE 다른 두 GONE으로 보여 주었다된다.
  2. F2 (에뮬레이터로 작업합니다)를 클릭하고 Settings (설정)를 클릭하십시오. 설정 메뉴가 열리고 드롭 다운에서 다른 옵션을 선택합니다.
  3. activity_main으로 돌아 가면 (Esc를 뒤로 사용) 아무 것도 변경되지 않았습니다.
  4. 그러나 F2로 설정 메뉴를 다시 열고 설정을 다시 변경 한 다음 main_layout으로 돌아 가면 버튼이 2 단계에서 선택한 설정으로 변경되었습니다.

내 질문 : 변경된 환경 설정으로 공개 여부가 변경된 후 내 main_layout을 "새로 고침"하려면 어떻게해야합니까? (내가 다시 갈 때 어떻게 바로 activity_main에 대한 변경 사항을 표시합니다.)

내가 MainActivity@Override onResume() 방법을 추가하고 "새로 고침"어떤 종류의 전화를해야이?

미리 답변 해 주셔서 감사합니다.

MainActivity.java :

public class MainActivity extends ActionBarActivity 
{ 
    ... 

    // Public static MainActivity so we can use findViewById from MyPrefsActivity 
    public static MainActivity mActivity; 

    public static final String LIST_PREFERENCE = "prefCheckboxOption"; 
    public static String currentValue; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     ... 

     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
     currentValue = preferences.getString(LIST_PREFERENCE, "0"); 

     setChosenPreference(Integer.valueOf(currentValue)); 

     mActivity = this; 
    } 

    public void setChosenPreference(int chosen_value){ 
     // First put all Visibilities on GONE 
     cbButton.setVisibility(View.GONE); 
     spinnerButton.setVisibility(View.GONE); 
     popupButton.setVisibility(View.GONE); 

     // Then turn the chosen on VISIBLE again 
     switch(chosen_value){ 
      case 0: // Multi-Click CheckBox 
      default: 
       cbButton.setVisibility(View.VISIBLE); 
       break; 
      case 1: // Dropdown CheckBox 
       spinnerButton.setVisibility(View.VISIBLE); 
       break; 
      case 2: // Pop-up CheckBox 
       popupButton.setVisibility(View.VISIBLE); 
       break;   
     } 
    } 

    ... 

    @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(); 
     switch(id){ 
      case R.id.action_settings: 
       startActivity(new Intent(this, MyPrefsActivity.class)); 
       return true; 
     } 
     return false; 
    } 
} 

MyPrefsActivity.java :

public class MyPrefsActivity extends PreferenceActivity 
{ 
    private static int prefs = R.xml.settings; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     MyPreferenceFragment pf = new MyPreferenceFragment(); 
     getFragmentManager().beginTransaction().replace(android.R.id.content, pf).commit(); 
    } 

    public static class MyPreferenceFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener 
    {  
     @Override 
     public void onCreate(Bundle savedInstanceState){ 
      super.onCreate(savedInstanceState); 
      addPreferencesFromResource(MyPrefsActivity.prefs); // outer class 
      // private members seem to be visible for inner class, and 
      // making it static made things so much easier 

      SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); 
      preferences.registerOnSharedPreferenceChangeListener(this); 

      MainActivity.mActivity.setChosenPreference(Integer.valueOf(MainActivity.currentValue)); 
     } 

     @Override 
     public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { 
      if(key.equals(MainActivity.LIST_PREFERENCE)){ 
       ListPreference listPreference = (ListPreference) findPreference(key); // LIST_PREFERENCE 
       if(listPreference != null){ 
        listPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { 
         @Override 
         public boolean onPreferenceChange(Preference preference, Object newValue) { 
          MainActivity.currentValue = (String) newValue; 
          MainActivity.mActivity.setChosenPreference(Integer.valueOf(MainActivity.currentValue)); 
          return false; 
         } 
        }); 
       } 
       else 
        Log.e("MyPrefsActivity", "listPreference is null!"); 
      } 
      else{ 
       // Other settings 
      } 
     } 
    } 
} 

activity_main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/main_layout" 
    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" 
    android:orientation="vertical" 
    tools:context="com.example.testproject.MainActivity$PlaceholderFragment" > 

    <ImageButton 
     android:id="@+id/ibtnCheckbox" 
     android:visibility="visible" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginBottom="15dp" 
     android:contentDescription="@string/checkbox_content_description" 
     android:src="@drawable/checkbox_unchecked" 
     android:background="@drawable/transparent_background" /> 

    <ImageButton 
     android:id="@+id/ibtnSpinner" 
     android:visibility="gone" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginBottom="15dp" 
     android:contentDescription="@string/checkbox_content_description" 
     android:src="@drawable/checkbox_unchecked" 
     android:background="@drawable/transparent_background" /> 

    <ImageButton 
     android:id="@+id/ibtnPopup" 
     android:visibility="gone" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginBottom="15dp" 
     android:contentDescription="@string/checkbox_content_description" 
     android:src="@drawable/checkbox_unchecked" 
     android:background="@drawable/transparent_background" /> 

</LinearLayout> 
012 여기

내 코드입니다 3,516,

Settings.XML이 :

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > 

    <PreferenceCategory android:title="@string/checkbox_options_title" > 
     <ListPreference 
       android:key="prefCheckboxOption" 
       android:title="@string/pref_checkbox_option" 
       android:summary="@string/checkbox_options_summary" 
       android:entries="@array/checkbox_options" 
       android:entryValues="@array/checkbox_option_values" /> 

    </PreferenceCategory> 

</PreferenceScreen> 

arrays.xml :

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string-array name="checkbox_options"> 
     <item>CheckBox as Multi-Click</item> 
     <item>CheckBox as Dropdown</item> 
     <item>CheckBox as Pop-up</item> 
    </string-array> 
    <string-array name="checkbox_option_values"> 
     <item>0</item> 
     <item>1</item> 
     <item>2</item> 
    </string-array> 
</resources> 

EDIT :

MainActivity.java

가 첨가 onResume() 방법을 제외하고, 정확히 동일하다 : 다른 참조로서 as Sir SC 게시했습니다.

및 MyPrefsActivity.자바는 훨씬 짧은 버전으로 변경되었습니다

public class MyPrefsActivity extends PreferenceActivity 
{ 
    private static int prefs = R.xml.settings; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit(); 
    } 

    public static class MyPreferenceFragment extends PreferenceFragment 
    {  
     @Override 
     public void onCreate(Bundle savedInstanceState){ 
      super.onCreate(savedInstanceState); 
      addPreferencesFromResource(MyPrefsActivity.prefs); // outer class 
      // private members seem to be visible for inner class, and 
      // making it static made things so much easier 
     } 
    } 
} 

답변

2

이 MainActivity 내부 onResume() 함수를 만듭니다.

onResume() 함수의 변경 내용을 설정하면 다른 활동에서 뒤로 누르면 MainActivity의 onResume이 호출되고 그 안에 작성한 설정이 표시됩니다. 나는 당신의 예에서 알고있는 것처럼

은 다음과 같이해야합니다 :

@Override 
protected void onResume() { 
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
    currentValue = preferences.getString(LIST_PREFERENCE, "0"); 
    setChosenPreference(Integer.valueOf(currentValue)); 
    super.onResume(); 
} 
+0

좋아, 덕분에 트릭을했던 그. 이제는 onResume 메소드에서만 setChosenPreference를 약 3 번 호출하기 때문에 복제 된 코드를 제거해야합니다. –