开发者

Change the Background of a Specific Preference Item

I have a preference group called "Credentials" and I'd like to change the color of that header based on whether the credentials are valid or not.

I keep a reference to the credentials item by grabbing it when I start up my PreferenceActivity

// ... code ...
public enum CredentialsInfo {
    VALID, INVALID, UNKNOWN
}

private Preference credentials;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.my_preferences);

    credentials = findPreference(getString(R.string.credentials));
    // ... etc ...
}

Once I am done verifying my credentials I run a function called updateCredentialsBarColor that is supposed to load the correct drawable and set the credentials Preference to the appropriate color. Though when I try to change the color nothing happens. Am I getting the view incorrectly and if so, what is the proper way to get it?开发者_开发知识库

private void updateCreditialsBarColor(CredentialsInfo state) {
    Drawable background = null;
    switch(state) {
    case VALID:
        background = getResources().getDrawable(R.drawable.credentials_state_valid);
        break;
    case INVALID:
        background = getResources().getDrawable(R.drawable.credentials_state_invalid);
        break;
    case UNKNOWN:
    default:
        background = getResources().getDrawable(R.drawable.credentials_state_unknown);
        break;
    }
    if(background != null) {
        View credentialsView = credentials.getView(null, null);
        credentialsView.setBackgroundDrawable(background);
    }
}


Um, that looks good. Are you sure updateCreditialsBarColor() gets called? After all, there's a typo in the method name, AFAICT.

You might also dump some logging information in that method and compare it to the results of examining your activity in Hierarchy Viewer to see if you're getting the View you think you are.

You might also consider creating a custom subclass of whatever Preference this is that encapsulates this behavior.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜