0

好吧,我在 A 类中有一个菜单方法,单击时会在模拟器中显示菜单。

如何将该方法用于我的新 B 类

我希望 B 类也可以使用这种方法:

public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //inflates the menu or this will show the activity
    MenuInflater awesome = getMenuInflater();
    awesome.inflate(R.menu.main, menu); //main is the xml main

    return true;
}

//this will manipulate the menu
public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()) {
    case R.id.menuSweet:
        startActivity(new Intent("Sweet"));
        return true;

    case R.id.menuToast:
        Toast andEggs = Toast.makeText(MainActivity.this,
        "This is a toast", Toast.LENGTH_LONG);
        andEggs.show();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }

}
4

2 回答 2

3

根据您想要做的事情,您通常有两个大选择(其中很多):子类化和组合:

子类化

因此,如果您的 B 类是 A 类行为的特化(B是 A 的特例),请扩展 A 类:

class A {
   public boolean onOptionsItemSelected(MenuItem item);
}

class B extends A {
   // some methods only B has.
}

因此你可以打电话

B b = new B();
b.onOptionsItemSelected(someItem);

作品

第二个选项是用它自己的同名方法包装对 A 的方法调用(所以 B有一个A 对象并使用它):

class B {
    private A a = new A();

    public boolean onOptionsItemSelected(Item someItem) {
       a.onOptionsItemSelected(someItem);
    }
}
于 2013-04-05T07:59:36.773 回答
0

如果我没有误会,你期待吗?

class A
{
    public boolean menu(){
        System.out.println("Inside Menu");
        return true;
    }
}
class B
{
    public void testMethod()
    {
        A a = new A();
        System.out.println(a.menu());
    }
}
public class Test
{
    public static void main(String[] args) {
        B b =new B();
        b.testMethod();
    }
}
于 2013-04-05T07:55:48.983 回答