webview.clearCache from PreferenceActivity

2019-02-20 09:07发布

I have preferences.xml which is used in my extension of PreferencesActivity.

I have another preference in the xml that I would like to use to clear the cache of a webview.

It has a key though I can't work out how to fire webview.clearCache by pressing the entry in my preferences...

In a nutshell, I'd like to run the webview.clearCache() command from a my preferences screen like one can from an options menu item.

OK so I think I have to use something like setOnPreferenceClickListener with onPreferenceClick, but how?

2条回答
We Are One
2楼-- · 2019-02-20 09:39

Solved by adding:

    Preference myPref = findPreference("myPref");
    myPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            MyActivity.mWebView.clearCache(true);
            return false;
        }
    });
查看更多
Summer. ? 凉城
3楼-- · 2019-02-20 09:53

Thanks for your own answer :) It was usefull for me.

In addition: below is the code when you want to delete a directory/folder on the sd-card from your xml-style preferences:

    public class Preferences extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        Preference myPref = findPreference("myPref");
        myPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference preference) {
                File sdcard = Environment.getExternalStorageDirectory();
                String sdcardPath = sdcard.getAbsolutePath();
                File mDbFile = new File(sdcardPath + "/myPath/");
                if(mDbFile.exists()) {
                    deleteDirectory(mDbFile);
                }
                return false;
            }
        });
    }

    private static boolean deleteDirectory(File path) {
        if( path.exists() ) {
          File[] files = path.listFiles();
          for(int i=0; i<files.length; i++) {
             if(files[i].isDirectory()) {
               deleteDirectory(files[i]);
             }
             else {
               files[i].delete();
             }
          }
        }
        return( path.delete() );
      }
}
查看更多
登录 后发表回答