1

PreferenceScreen에 액세스하면 사용자 지정 스위치가 꺼져 있음을 알 수 있습니다. 그런 다음 앱을 켜고 앱을 다시 시작합니다. PreferenceScreen으로 돌아가 스위치가 다시 작동합니다. 이것은 기본 SwitchPreference를 사용할 때 발생하지 않습니다. SwitchPreference를 원하는 방식으로 사용자 정의 할 수 있으므로 유일한 문제는 저장하지 않는 스위치 값입니다.사용자 지정 SwitchPreference 값을 저장하지 않음

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

    <com.example.CustomSwitchPreference 
     android:key="vibration" 
     android:title="vibration" 
     android:summary="" 
     android:defaultValue="true" /> 

</PreferenceScreen> 

CustomSwitchPreference.java : 나는 PreferenceFragment

SettingsFragment.java

public class SettingsFragment extends PreferenceFragment { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // Load the preferences from an XML resource 
     addPreferencesFromResource(R.xml.preferences); 
    } 

} 

preferences.xml로의 확장에 배치되어 사용자 정의 SwitchPreference과 환경 모두에 관련된 네 개의 파일이 :

public class CustomSwitchPreference extends SwitchPreference { 
    public CustomSwitchPreference(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public CustomSwitchPreference(Context context) { 
     super(context); 
    } 


    @Override 
    protected View onCreateView(ViewGroup parent) 
    { 
     LayoutInflater li = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     return li.inflate(R.layout.customswitch_preference, parent, false); 
    } 

    /* 
    @Override 
    protected void onBindView(View view) { 
     MainActivity mainActivity = (MainActivity)getContext(); 
     RelativeLayout relativeLayout = (RelativeLayout)mainActivity.findViewById(R.id.switch_frame); 
     Switch s = (Switch)relativeLayout.getChildAt(1); 
     s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      @Override 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       persistBoolean(isChecked); 
      } 
     }); 
     super.onBindView(view); 
    } 
    */ 

} 

customswitch_preferenc e.xml :

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/switch_frame" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    > 

    <TextView 
     android:id="@+id/switch_title" 
     android:textSize="18sp" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Title" 
     android:layout_alignParentStart="true"/> 


    <Switch 
     android:id="@+id/switch_pref" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentEnd="true" 
     /> 

</RelativeLayout> 

MainActivity.java :

public class MainActivity extends Activity { 

    private ActionBar actionBar; 
    private boolean mInit = false; 
    private boolean showIcon = true; 
    private Menu m; 
    private GridFragment gridFragment; 
    private SettingsFragment settingsFragment; 
    public ImageButton startButton; 
    public TextView gameTimer; 
    public TextView mineCount; 
    public boolean isVibrating; 

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

     setContentView(R.layout.activity_main); 
     settingsFragment = new SettingsFragment(); 
     actionBar = getActionBar(); 
     actionBar.setTitle("Settings"); 
     actionBar.setCustomView(R.layout.actionbar); 
     //actionBar.setDisplayShowTitleEnabled(false); 
     actionBar.setDisplayShowCustomEnabled(true); 
     actionBar.setDisplayUseLogoEnabled(false); 
     actionBar.setDisplayShowHomeEnabled(false); 
     //actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK)); 
     ViewGroup actionBarViews = (ViewGroup)actionBar.getCustomView(); 
     startButton = (ImageButton)(actionBarViews.findViewById(R.id.actionBarLogo)); 
     mineCount = (TextView)actionBarViews.findViewById(R.id.topTextViewLeft); 
     gameTimer = (TextView)actionBarViews.findViewById(R.id.topTextViewRight); 
     startButton.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       switch(event.getAction()){ 
        case MotionEvent.ACTION_DOWN: 
         startButton.setImageResource(R.drawable.smiley2); 
         break; 
        case MotionEvent.ACTION_UP: 
         restartGame(); 
         break; 
       } 
       return false; 
      } 
     }); 

     Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/digital-7 (mono).ttf"); 
     TextView textView; 
     int[] resources = 
       {R.id.textViewLeft,R.id.topTextViewLeft,R.id.textViewRight,R.id.topTextViewRight}; 
     for(int r: resources) { 
      textView = (TextView) findViewById(r); 
      textView.setTypeface(myTypeface); 
     } 

     if (findViewById(R.id.fragment_container) != null){ 
      if (savedInstanceState != null) { 
       return; 
      } 
     } 
    } 

    public void restartGame() { 
     startButton.setImageResource(R.drawable.smiley); 
     getFragmentManager().beginTransaction().remove(gridFragment).commit(); 
     setText(999, gameTimer); 
     startGame(); 
    } 

    private void startGame(){ 

     gridFragment = new GridFragment(); 

     gridFragment.setArguments(getIntent().getExtras()); 

     getFragmentManager().beginTransaction().add(R.id.fragment_container, gridFragment,"gridFragment").commit(); 

    } 

    public void setText(int value, TextView textView){ 
     value = Math.min(999,value); 
     value = Math.max(-99,value); 
     textView.setText(String.format("%03d",value)); 
    } 

    @Override 
    protected void onStart() { 
     if (!mInit) { 
      mInit = true; 
      Database db = new Database(this); 
      db.deleteAllSessions(); 
      db.close(); 
      startGame(); 
     } 
     super.onStart(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     m = menu; 
     return true; 
    } 

    private void openSettings(){ 
     showIcon = false; 
     gridFragment.pauseTimer(); 
     onPrepareOptionsMenu(m); 
     actionBar.setDisplayShowCustomEnabled(false); 
     FragmentTransaction ft = getFragmentManager().beginTransaction(); 
     ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); 
     ft.hide(gridFragment); 
     ft.add(android.R.id.content, settingsFragment).commit(); 
     //ft.replace(android.R.id.content,settingsFragment); 
    } 

    private void updateSettings(){ 

     SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); 

     Map<String, ?> map = sharedPrefs.getAll(); 
     for (Map.Entry<String, ?> entry : map.entrySet()) { 
      Log.d("map values", entry.getKey() + ": " + entry.getValue().toString()); 
     } 
     isVibrating = (Boolean)map.get("vibration"); 
    } 

    private void closeSettings(){ 
     showIcon = true; 
     onPrepareOptionsMenu(m); 
     actionBar.setDisplayShowCustomEnabled(true); 
     FragmentTransaction ft = getFragmentManager().beginTransaction(); 
     ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); 
     ft.show(gridFragment); 
     ft.remove(settingsFragment).commit(); 
     //ft.replace(android.R.id.content,gridFragment); 
     gridFragment.resumeTimer(); 
    } 

    @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(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      openSettings(); 
      return true; 
     } 
     else if(id == R.id.backButton){ 
      updateSettings(); 
      closeSettings(); 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    @Override 
    public boolean onPrepareOptionsMenu(Menu menu) { 
     MenuItem item= menu.findItem(R.id.action_settings); 
     item.setVisible(showIcon); 
     item = menu.findItem(R.id.backButton); 
     item.setVisible(!showIcon); 
     return super.onPrepareOptionsMenu(menu); 
    } 
} 
+0

나는 귀하의 활동 코드를 원합니다. – Akash

+0

@DerGolem : onCreateView() 만 재정의 했으므로 이미 그렇게하지 않았습니까? 활동 코드 게시 중 ... – user2361174

답변

0

당신은 결코 실제로 설정하거나 스위치의 상태를 저장하고 있습니다. 뷰의 초기 상태를 설정하려면 onBindView을 무시하고 스위치 (R.id.switch_pref)에 확인 된 변경 수신기를 연결하여 변경 사항을 수신하고이를 SharedPreferences에 유지해야합니다 (이를 수행하려면 persistBoolean이라고 할 수 있음).

+0

내 코드에'onBindView'를 추가했는데,'relativeLayout'이 null을 반환한다는 것이 문제입니다. 코드에서 R.id.switch_pref 스위치에 액세스 할 수 있습니까? – user2361174

관련 문제