16

我有一个设置如下的 ToggleButton:

final ToggleButton filterButton = (ToggleButton) findViewById(R.id.filterTags);
        filterButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (filterButton.isChecked()) {
                    // pop up the list of tags so the user can choose which to filter by
                    // once one is chosen, the spinner will be updated appropriately
                    showDialog(DIALOG_TAGS);
                } else {
                    // going unpressed, set the the spinner list to everything
                    updateSpinner(db.itemNames());
                }
            }
        });

对话框如下所示:

   case DIALOG_TAGS:
        final String[] tagNames = db.tagNamesInUse();
        dialog = new AlertDialog.Builder(this)
            .setItems(tagNames, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        updateSpinner(db.getItemNamesForTag(tagNames[which]));
                        final ToggleButton filterButton = (ToggleButton) findViewById(R.id.filterTags);
                        filterButton.setTextOn(tagNames[which]);
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("Cancel", UITools.getDialogCancellingListener())
            .create();

这个想法是:如果打开了 ToggleButton,它会弹出一个单选列表视图对话框,即标签列表。一旦选择了一个标签,它就会成为 ToggleButton 的新 textOn。如果 ToggleButton 已关闭(未选中),则文本将恢复为静态 TextOff。

问题是:一旦对话框消失,按钮就不会被重绘。显示的文本仍然是 textOn 的先前值。

如何强制重绘?我试过filterButton.postInvalidate();了,但这没有帮助。

4

1 回答 1

20

解决了!明智地阅读 ToggleButton 的源代码表明,虽然 setTextOn() 和 setTextOff() 不会导致对更新 TextView 位的(私有)syncTextState 的调用,但调用 setChecked()。所以诀窍是:

dialog = new AlertDialog.Builder(this)
            .setItems(tagNames, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        updateSpinner(db.getItemNamesForTag(tagNames[which]));
                        final ToggleButton filterButton = (ToggleButton) findViewById(R.id.filterTags);
                        filterButton.setTextOn(tagNames[which]);
                        filterButton.setChecked(filterButton.isChecked());
                        dialog.dismiss();
                    }
                })

效果很好。支持开源!

于 2010-09-25T04:58:29.647 回答