选中文本视图以切换首选项

时间:2017-10-03 20:58:01

标签: android android-checkedtextview

你好我想改变我的选中文本视图来切换首选项 我应该使用哪种方法是我的选中文本查看方法 我想做同样的事情,但有切换偏好

final CheckedTextView cc = (CheckedTextView) findViewById(R.id.checkedTextView);
    if (!mysetting.service) {
        ctv.setChecked(false);
    } else if (mysetting.service) {
        ctv.setChecked(true);
    }
    ctv.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (ctv.isChecked()) {
                mysetting.service = false;
                ctv.setChecked(false);
                Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
                editor.putBoolean("service", false);
                editor.commit();
                return;
            }
            ctv.setChecked(true);
            mysetting.service = true;
            editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
            editor.putBoolean("service", true);
            editor.commit();
        }

2 个答案:

答案 0 :(得分:0)

一旦此视图为CompoundButton(link),强烈建议使用setOnCheckedChangeListener打开(选中)或关闭(取消选中):

    switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if(ischecked){
      //do something if is checked
    }else{
     //do something if is unchecked
    }
}

});

答案 1 :(得分:0)

private boolean serviceEnable = false;

    public boolean isServiceEnable() {
        return serviceEnable;
    }

    public void setServiceEnable(boolean serviceEnable) {
        this.serviceEnable = serviceEnable;
    }

    private void savePreference() {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
        editor.putBoolean("service", isServiceEnable());
        editor.commit();
    }

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

        setContentView(R.layout.checked_textview);

        final CheckedTextView cc = (CheckedTextView) findViewById(R.id.check_text_view);
        cc.setChecked(isServiceEnable());

        cc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setServiceEnable(!isServiceEnable());
                cc.setChecked(isServiceEnable());
                savePreference();
            }
        });
    }

我希望它可以帮到你