2014-09-02 96 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); 

} 
相關問題