Use same method for all option menu in whole Appli

2019-10-03 06:44发布

I have 10 to 12 Activity, All Activity has Help Menu as an Option Menu. I am succeed with following code to create it and showing help on click of them.

    Intent intent = new Intent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(new File(cacheDir, "HELP.pdf")),"application/pdf");

    context.startActivity(intent);

But I want to Reduce this code for all Activity, and for that i have created one class and make one method but still i want to reduce code.

I have searched and found that onClick attribute is available in OptionMenu but I didn't get how to use it.

Please Help..

2条回答
女痞
2楼-- · 2019-10-03 06:50

Create a class, for example call it Helper, where you put a method called handleMenu(int id) and where you do all the work. Then, in every activity you call that method from onOptionsItemSelected(), passing the id of the item selected.

查看更多
男人必须洒脱
3楼-- · 2019-10-03 06:54

I have created following Class for openFile:

public class OpenHelpFile {

    File cacheDir;
    Context context;

    /* Constructor */
    public OpenHelpFile(Context context) {
        this.context = context;

        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "OOPS");
        else
            cacheDir = context.getCacheDir();

        if (!cacheDir.exists())
            cacheDir.mkdirs();

        try {
            File helpFile = new File(cacheDir, "OOPS.pdf");

            if (!helpFile.exists()) {
                InputStream in = context.getAssets().open("OOPS.pdf");
                OutputStream out = new FileOutputStream(helpFile);

                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();

                Log.d(TAG, "File Copied...");
            }
            Log.d(TAG, "File exist...");

        } catch (FileNotFoundException ex) {
            Log.d(TAG, ex.getMessage() + " in the specified directory.");
            System.exit(0);
        } catch (IOException e) {
            Log.d(TAG, e.getMessage());
        }
    }

    public void openHelpFile() {

        /* OPEN PDF File in Viewer */
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(cacheDir, "OOPS.pdf")), "application/pdf");

        context.startActivity(intent);
    }
}

and I have call it from every OptionMenu like this:

new OpenHelpFile(context).openHelpFile();
查看更多
登录 后发表回答