我可以问为什么在这种情况下我们必须使用匿名内部类而不是传统方式?
@Override
public boolean OnCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(R.string.external_url);
item.setOnMenuItemClickListener(new MenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item){
String webpage = "http://developer.android.com/index.html";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent);
return false;
}
});
return super.OnCreateOptionsMenu(menu);
}
答案 0 :(得分:0)
MenuItemClickListener listener = new MenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item){
String webpage = "http://developer.android.com/index.html";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent);
return false;
}
});
item.setOnMenuItemClickListener(listener);
答案 1 :(得分:0)
你不必这样做,它只是倾向于更紧凑和简洁。如果你愿意,你可以这样做:
@Override
public boolean OnCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(R.string.external_url);
item.setOnMenuItemClickListener(menuClickListener);
return super.OnCreateOptionsMenu(menu);
}
private MenuItemClickListener menuClickListener = new MenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item){
String webpage = "http://developer.android.com/index.html";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent);
return false;
}
}
这仍然是一个匿名类,我只移动了它的声明并将其分配给私有成员变量。如果要在多个项目上设置它,这可能很有用。
如果您不希望它是匿名的,您可以创建一个内部类:
@Override
public boolean OnCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(R.string.external_url);
item.setOnMenuItemClickListener(new MyMenuClickListener());
return super.OnCreateOptionsMenu(menu);
}
private class MyMenuClickListener implements MenuItemClickListener {
@Override
public boolean onMenuItemClick(MenuItem item){
String webpage = "http://developer.android.com/index.html";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent);
return false;
}
}
最后,你可以让你的Activity / Fragment实现MenuItemClickListener
:
public class MyActivity extends Activity implements MenuItemClickListener {
/* ... */
@Override
public boolean OnCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(R.string.external_url);
item.setOnMenuItemClickListener(this);
return super.OnCreateOptionsMenu(menu);
}
@Override
public boolean onMenuItemClick(MenuItem item){
String webpage = "http://developer.android.com/index.html";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent);
return false;
}
}