2010-08-25 4 views
10

Quindi, durante determinati stati della mia app, voglio disabilitare determinate CheckBoxPreferences nel mio menu di impostazione. Tuttavia, se l'utente fa clic su di essi, voglio che venga mostrato un brindisi esplicativo. Se faccio solo setEnable (false); su CheckBoxPreference, ottengo l'aspetto giusto. Ma non posso ottenere un brindisi per essere mostrato al clic. D'altra parte, ho fallito nel fare manualmente un CheckBoxPreference come se fosse disabilitato.Rendi l'aspetto delle preferenze disattivato, ma continua a registrare i clic

risposta

18

Invece di disabilitare la preferenza, è possibile disabilitare anche le visualizzazioni della preferenza.

public class DisabledAppearanceCheckboxPreference extends CheckBoxPreference { 

     protected boolean mEnabledAppearance = false; 

     public DisabledAppearanceCheckboxPreference(Context context, 
       AttributeSet attrs) { 
      super(context, attrs); 

     } 
    @Override 
    protected void onBindView(View view) { 
     super.onBindView(view); 
     boolean viewEnabled = isEnabled()&&mEnabledAppearance; 
     enableView(view, viewEnabled); 
    } 

    protected void enableView(View view, boolean enabled){ 
     view.setEnabled(enabled); 
     if (view instanceof ViewGroup){ 
      ViewGroup grp = (ViewGroup)view; 
      for (int index = 0; index < grp.getChildCount(); index++) 
       enableView(grp.getChildAt(index), enabled); 
     } 
    } 
    public void setEnabledAppearance(boolean enabled){ 
     mEnabledAppearance = enabled; 
     notifyChanged(); 
    } 
    @Override 
    protected void onClick() { 
     if (mEnabledAppearance) 
      super.onClick(); 
     else{ 
      // show your toast here 
     } 
    } 

} 
+0

soluzione creativa e ordinato, grazie! – pgsandstrom

0

Anche se la vostra preferenza è disabilitata, è possibile ricevere OnTouchEvents:

public class MyPreferenceFragment extends PreferenceFragment { 

    ... 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

     View view = super.onCreateView(inflater, container, savedInstanceState); 
     final ListView listView = (ListView) view.findViewById(android.R.id.list); 

     listView.setOnTouchListener(new OnTouchListener() { 

      @Override 
      public boolean onTouch(View view, MotionEvent event) { 

       int position = listView.pointToPosition((int) event.getX(), (int) event.getY()); 
       ListAdapter adapter = listView.getAdapter(); 
       Preference preference = (Preference) adapter.getItem(position); 

       if (!preference.isEnabled()) 
        Toast.makeText(getActivity(), "Sorry, this setting is not available!", Toast.LENGTH_LONG).show(); 

       return false; 
      } 
     }); 


     return view; 
    } 

    ... 
}