【问题标题】:How to get checked button position in Android MaterialButtonToggleGroup如何在 Android MaterialButtonToggleGroup 中检查按钮位置
【发布时间】:2020-09-17 03:59:57
【问题描述】:

我在我的xml中定义了一个MaterialButtonToggleGroup和2个MaterialButton,这样:

<com.google.android.material.button.MaterialButtonToggleGroup
    ...
    app:checkedButton="@+id/favorite_color1"
    app:singleSelection="true">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/favorite_color1"
        ... />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/favorite_color2"
        ... />

</com.google.android.material.button.MaterialButtonToggleGroup>

我找到了getCheckedButtonIds() 方法(返回一个ID 列表)和OnButtonCheckedListener(返回一个整数ID),但是get(int index) 方法返回索引位置的视图,而不是具有特定ID 的视图.

我怎样才能(以编程方式)在给定时刻获得选中按钮的视图? 有没有方法返回当前检查的位置(或索引)?

【问题讨论】:

    标签: android material-design android-button android-togglebutton materialbutton


    【解决方案1】:

    由于您使用的是app:singleSelection="true",因此您可以使用getCheckedButtonId() 方法获取该组中所选MaterialButton 的唯一ID。
    你可以使用类似的东西:

    MaterialButtonToggleGroup materialButtonToggleGroup = 
             findViewById(R.id.toggle_button_group);
    int buttonId = materialButtonToggleGroup.getCheckedButtonId();
    MaterialButton button = materialButtonToggleGroup.findViewById(buttonId);
    

    您也可以使用getCheckedButtonIds() 并循环遍历ID。

    List<Integer> ids = materialButtonToggleGroup.getCheckedButtonIds();
    for (Integer id:ids){
          MaterialButton materialButton = materialButtonToggleGroup.findViewById(id);
          //....
    }
    

    【讨论】:

    • 是的,我认为这是目前最好的解决方案。但奇怪的是,Android 没有提供返回选定索引列表以通过 get(index) 方法获取选定视图的方法。
    • @capo11 MaterialButtonToggleGroup 不适用于索引(作为数组)。所有方法(例如checkuncheck)都适用于 ID 视图。
    • 是的,我知道。只有一种方法适用于索引(目前):get(index: Int)。这个方法对我来说非常有用,因为它返回一个视图。而且我想精确地操作该视图,但我必须实现一个循环来确定哪些 idex 与所选视图相关。我本来希望找到像这样的另一种方法:get(id: Int)return View。
    • 方法get(index)ViewGroup继承的,不是MaterialButtonToggleGroup特有的
    猜你喜欢
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多