Search code examples
androidcopypreferenceactivity

Automatically copy text in a Preference Screen


This might have been asked before, but I have searched all over for an answer to this and can't find one.

I have a PreferenceScreen in my Android app with a list of EditTextPreferences that I set the value of programmatically in my code. One of these values should not be editable however, but the user must be able to copy the value (to paste on in a specific field on a website). In its current state the user can change it, but I don't want that to happen.

I have tried looking into using android:inputType="none" but it seems that doesn't work.

I came up with a different idea, but I'm not sure if that will work. Can I make it so that when the user clicks on the field it automatically copies the value (and probably shows a toast saying "value copied" or something) so they can paste it somewhere else? Then I could just make it into a regular preference field or something and not have to worry about the user changing the value!

can anyone give me any tips regarding this?


Solution

  • Yes that is possible.

    Make it a <Preference>

    After that you can add an on click listener like

        getPreferenceScreen().findPreference(prefkey)
            .setOnPreferenceClickListener(new OnPreferenceClickListener(){
            public boolean onPreferenceClick(Preference preference)
            {   
                String oldValue = sharedPreferences.getString(prefkey, prefdefaultvalue);
    
                // You can do what you want here like copy value to clipboard and display toast
    
            return true;
            }});