In preferences, select my sound just like with RingtonePreference

前端 未结 4 869
灰色年华
灰色年华 2020-12-13 11:33

I have sounds in my /raw folder and I would like my user to be able to choose one sound in preferences exactly like RingtonePreference does but only with my sounds.

4条回答
  •  悲哀的现实
    2020-12-13 12:00

    So finally I looked into the source code of ListPreference and made the same with some modifcations. As I can't use com.android.internal.R.styleable.ListPreference I had to create my own styleable in attrs.xml :

    
    
        
            
            
        
        
            
        
    
    

    and then import it in my preferences.xml file like this:

     xmlns:foo="http://schemas.android.com/apk/res/com.abe.abemoto"
    

    and uses it :

        
    

    In my class CustomSoundListPreference I modified the method onPrepareDialogBuilder to play my sound on item clicked.

        @Override
    protected void onPrepareDialogBuilder(Builder builder) {
        super.onPrepareDialogBuilder(builder);
    
        mMediaPlayer = new MediaPlayer();
    
        if (mEntries == null || mEntryValues == null) {
            throw new IllegalStateException(
                    "ListPreference requires an entries array and an entryValues array.");
        }
    
        mClickedDialogEntryIndex = getValueIndex();
        builder.setSingleChoiceItems(mEntries, mClickedDialogEntryIndex,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        mClickedDialogEntryIndex = which;
    
                        String value = mEntryValues[which].toString();
    
                        Resources res = getContext().getResources();
                        int resId = res.getIdentifier(value, "raw",
                                getContext().getPackageName());
    
                        Uri uri = Uri.parse(String.format(getContext()
                                .getString(R.string.resource_sound),
                                getContext().getPackageName(), resId));
    
                        Log.d(TAG, "uri sound = " + uri);
                        try {
                            mMediaPlayer.reset();
                            mMediaPlayer.setDataSource(getContext(), uri);
                            mMediaPlayer.prepare();
                            mMediaPlayer.start();
    
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
    
                    }
                });
    
        builder.setPositiveButton("Ok", this);
        builder.setNegativeButton("Annuler", this);
    }
    

提交回复
热议问题