【问题标题】:Need to access properties of extended ToggleButton class through OnCheckChangedListener需要通过 OnCheckChangedListener 访问扩展 ToggleButton 类的属性
【发布时间】:2015-04-07 17:57:20
【问题描述】:

我正在尝试将ToggleButton 类扩展为一个名为TagToggleButton 的新类,其唯一的区别是它有一个我可以设置与之关联的ID。 TagToggleButton 类如下所示:

public class TagToggleButton extends ToggleButton {

    private long tagId;

    public TagToggleButton(Context context) {
        super(context);
    }

    public TagToggleButton(Context context, long id) {
        super(context);
        this.setTagId(id);
    }

    public void setTagId(long id) {
        this.tagId = id;
    }

    public long getTagId() {
        return this.tagId;
    }

}

然后我想调用一个 OnClickListener 来获取按钮的 ID 属性。例如:

tag.setOnCheckedChangeListener(new TagToggleButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            long id = buttonView.getTagId();
            // will do something with id afterwards
        } else {
            //Will do something else if the button isn't checked
        }
    }

但是,我不能在buttonView 上调用getTagId,因为它被定义为CompoundButton。如何将buttonView 更改为TagToggleButton 的类型(即如何在TagToggleButton 方法中覆盖OnCheckedChangeListener 类?

非常感谢!

【问题讨论】:

  • 您是否尝试过在onCheckedChanged 方法中将CompoundButton buttonView 转换为TagToggleButton
  • @rere252 不,我没有,没有意识到这是有效的。我可以直接在我描述的 onCheckedChanged 方法中执行此操作吗? (因为我不需要进一步编辑 TagToggleButton 类?)
  • 我尝试了以下方法:long id = (TagToggleButton) buttonView.getTagId();,但它仍然作为 Android Studio 中未解决的方法出现
  • 试试((TagToggleButton) buttonView).getTagId();
  • 行得通!谢谢! @rere252 你能提交一个答案,然后我可以将其标记为正确吗?

标签: java android onclicklistener android-togglebutton


【解决方案1】:

onCheckedChanged 方法中,将CompoundButton buttonView 转换为TagToggleButton。要获取标签 ID,您可以执行 long id = ((TagToggleButton) buttonView).getTagId();

之类的操作

【讨论】:

    猜你喜欢
    • 2016-06-25
    • 2022-01-01
    • 2021-06-22
    • 2016-12-06
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    相关资源
    最近更新 更多