创建一个可重用的类

时间:2018-12-13 12:08:42

标签: java android class

我有一个在Android中运行的应用程序,我想创建一个菜单并在某些活动中重复执行,该菜单调用Intent来打开其他活动。

我该怎么做?

认为也许我可以创建一个类,但出现错误。我在哪里可以创建一个类?里面的onCreate方法? 我如何在其他活动中重复使用菜单?

谢谢!

这是我的菜单代码:

menu_button = (Button) findViewById(R.id.menu_button);
    menu_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PopupMenu popupMenu = new PopupMenu(MainActivity.this, menu_button);
            popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());

            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.one:
                            Intent vista = new Intent(MainActivity.this, openCamera.class);
                            MainActivity.this.startActivity(vista);

                    }
                    return true;

                    /*
                    Toast.makeText(MainActivity.this, "" + item.getTitle(), Toast.LENGTH_SHORT).show();
                    return true;
                    */
                }
            });
            popupMenu.show();
        }
    });

1 个答案:

答案 0 :(得分:1)

如果菜单始终是相同的,并且您想在多个活动中重复使用它,则只需这样定义即可:

public class TestMenu {

    private final PopupMenu popupMenu;

    public TestMenu(final Activity activity, View anchor) {
        popupMenu = new PopupMenu(activity, anchor);
        popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());

        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.one:
                        Intent vista = new Intent(activity, openCamera.class);
                        activity.startActivity(vista);
                }
                return true;
            }
        });
    }

    public void show() {
        popupMenu.show();
    }
}

然后像这样在您的活动中使用它:

public class TestActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Button menu_button = (Button) findViewById(R.id.menu_button);
        TestMenu myMenu = new TestMenu(this, menu_button);
        menu_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myMenu.show();
            }
        });
    }
}