2014-09-02 92 views
0

我想这样做:当CheckBoxPreference未选中时,CheckBoxPreference标题的文本颜色变为灰色,如果选中,标题的文本颜色将恢复为原始颜色(取决于主题)。如何更改android中CheckBoxPreference标题的文本颜色?

我到现在为止做了什么:我创建了一个新类,从CheckBoxPreference延伸。

public class CustomCheckBoxPreference extends CheckBoxPreference{ 

    TextView txtTitle; 
    int originalTextColor; 

    public CustomCheckBoxPreference(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    @Override 
    protected void onBindView(View view) { 

     txtTitle = (TextView) view.findViewById(android.R.id.title); 
     originalTextColor = txtTitle.getCurrentTextColor(); 

     setOnPreferenceClickListener(new OnPreferenceClickListener() { 
      @Override 
      public boolean onPreferenceClick(Preference preference) { 
       if (isChecked()) { 
        txtTitle.setTextColor(originalTextColor); //it doesn't work 
       } 
       else { 
        txtTitle.setTextColor(Color.GRAY); //it doesn't work 
       } 
       return true; 
      } 
     }); 

     super.onBindView(view); 
    } 
} 

当我运行应用程序时,txtTitle.setTextColor(..)显然没有奏效,文字颜色一点都没有改变。我也已经通过调试器确认调用了方法onPreferenceClick

+0

您正在使用检查isChecked()但它在哪里定义?而不是只使用icChecked()你需要使用((CheckBoxPreference)首选项).isChecked()用于检查目的 – 2014-10-08 11:20:24

+0

@RajenRaiyarela:我从CheckBoxPreference类扩展,这就是它的来源。 – null 2014-10-15 11:44:21

回答

0

即使我做了同样的事情,并没有为我工作,我也不知道原因。

但它会工作,如果你删除onPreferenceClickListener()和只有在其他情况下使用。

protected void onBindView(View view) { 

    txtTitle = (TextView) view.findViewById(android.R.id.title); 
    originalTextColor = txtTitle.getCurrentTextColor(); 


      if (isChecked()) { 
       txtTitle.setTextColor(originalTextColor); 
      } 
      else { 
       txtTitle.setTextColor(Color.GRAY); 
      } 
      return true; 

    super.onBindView(view); 

} 
相关问题