mauisamsung-mobilemaui-android

How can I remove the default tap sound that plays when tapping anywhere within a CollectionView's ItemTemplate on a Samsung Android device?


I have a CollectionView that has an ItemTemplate similar to the below:

<CollectionView>
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>

                <Label Grid.Column="0"
                       Text="{Binding Name}" />

                <Label Grid.Column="1"
                       Text="{Binding Cost}" />
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

On iOS, everything seems fine, whereas on Android, specifically my physical Samsung device, there is a default "tap" sound that plays whenever I tap anywhere within the bounds of the item.

I can disable the sound by adding an empty TapGestureRecognizer to the ItemTemplate like so:

<Grid>
    <Grid.GestureRecognizers>
        <TapGestureRecognizer />
    </Grid.GestureRecognizers>
</Grid>

This removes the sound but seems like a hack that I really don't want coming back to bite me sometime in the future, so I'd much prefer an actual solution.


Solution

  • So, the issue isn't across the board and seems to only affect some devices (in my case, Samsung). The best solution I found was to create a new style for the application that disables sound effects and apply that to the MainActivity. To do this, I created a new styles.xml file under Platforms/Android/Resources/values/ that contained the following:

    <resources>
      <style name="AppTheme" parent="Maui.SplashTheme">
        <!-- Tells the Android OS not to play OS-specific SFX -->
        <item name="android:soundEffectsEnabled">false</item>
      </style>
    </resources>
    

    Since Maui already defined a style that's frustratingly hidden from the user (see here), I went ahead and derived my style from that using the parent tag.

    After that, the only thing left to do to apply the style was to open MainActivity.cs and update the Activity attribute near the top of the file like so, using my style instead of the Maui one:

    [Activity(Theme = "@style/AppTheme", ...)]
    public class MainActivity : MauiAppCompatActivity
    {
        // Other app initialization stuff
    }
    

    This fixed the issue I was seeing. I will note that should you prefer, you could override the entire app's style instead of the individual Activity's by applying an Application attribute to the MainApplication.cs file, but this is only really necessary if your app has multiple Activities that need different styles.