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

pjz*_*pjz 16 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());
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)

对话框如下所示:

   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();
Run Code Online (Sandbox Code Playgroud)

这个想法是:如果打开ToggleButton,它会弹出一个单选列表视图对话框,它是标签列表.选择标记后,它将成为ToggleButton的新textOn.如果关闭ToggleButton(unChecked),则文本将恢复为静态TextOff.

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

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

pjz*_*pjz 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();
                    }
                })
Run Code Online (Sandbox Code Playgroud)

哪个工作得很好.耶和开源!