如何在android下运行动态ToggleButton文本?

时间:2010-09-24 04:57:57

标签: android dynamic togglebutton

我有一个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(unChecked),则文本将恢复为静态TextOff。

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

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

1 个答案:

答案 0 :(得分:19)

解决!明智地读取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();
                    }
                })

哪个效果很好。耶和开源!