使首选项看起来已禁用,但仍会注册点击次数

时间:2010-08-25 13:29:04

标签: android preferences

因此,在我的应用中的某些状态下,我想在设置菜单中禁用某些CheckBoxPreferences。但是,如果用户点击它们,我想要显示一个解释性的吐司。如果我只是做setEnable(false);在CheckBoxPreference上,我确实得到了正确的外观和感觉。但我不能在点击时显示祝酒词。另一方面,我无法手动使CheckBoxPreference看起来像被禁用。

2 个答案:

答案 0 :(得分:18)

您也可以禁用首选项的视图,而不是禁用首选项。

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
        }
    }

}

答案 1 :(得分:0)

即使您的偏好被禁用,您也可以收到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;
    }

    ...
}