android - 如何在 android 下获得工作的动态 ToggleButton 文本?

标签 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,它会弹出一个单选 ListView 对话框,即标签列表。一旦选择了一个标签,它就会成为 ToggleButton 的新 textOn。如果 ToggleButton 已关闭(未选中),则文本将恢复为静态 TextOff。

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

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

最佳答案

解决了!明智地阅读 ToggleButton 的源代码表明,虽然 setTextOn() 和 setTextOff() 不会导致对更新 TextView 位的(私有(private))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();
                    }
                })

效果很好。支持开源!

关于android - 如何在 android 下获得工作的动态 ToggleButton 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3784292/

相关文章:

c++ dynamic_cast 装饰器实例化失败

R : combine and save rgl widgets as a single html file

Android切换按钮以编程方式还是XML?

android - 无效/自签名证书上类似浏览器的行为

python - Python 模块的动态加载

r - dplyr 总结动态列

java - ToggleButton 阻止我的应用程序启动

android - 如何在特定时间设置 View 可见?

android - 添加项目时如何让 GridView 适应其高度

java - Android:如何绘制下载的位图,然后将其填充到 ImageView?