我有10个扩展baseActivity的活动。我的BaseActivity基本上有一个帮助菜单图标。当用户按下帮助菜单图标时,我应该显示该活动的帮助菜单。如何知道哪个活动称为帮助菜单,以便我知道要显示哪个xml资源
public class BaseActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.help_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.help_menu_item:
displayHelpMenu();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected void displayHelpMenu(){
// I will load the xml to the textview and display it in dialog. How can I know which xml resource to load
}
}
答案 0 :(得分:3)
查找Activity
的一种方法是使用instanceOf
。像这样:
protected void displayHelpMenu() {
// I will load the xml to the textview and display it in dialog.
// How can I know which xml resource to load
if(this instanceOf DerivedActivity.class) {
// load XML file
}
else if(...) {
...
}
}
但是,在我看来,虽然这解决了你的问题,但这不是正确的做事方式。在最终出现这种情况的OOP中,您应该使用方法覆盖。
base class
定义了加载资源的一般功能,而派生类应该提供要加载的文件的名称。换句话说,base class
不应该知道derived class
。更好的解决方案是:
protected void displayHelpMenu() {
// ask each child class for the help menu resource file
int resId = getHelpMenuResource();
// write code to load XML file with resId
...
...
}
protected int getHelpMenuResource() {
return defaultMenuId;
}
现在,在您的派生类中,@Override
getHelpMenuResource()
方法并返回特定于该活动的资源ID。
答案 1 :(得分:1)
如何使您的BaseActivity抽象并添加getMenuResource方法?
public abstract class BaseActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.help_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.help_menu_item:
displayHelpMenu();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected void displayHelpMenu(){
// I will load the xml to the textview and display it in dialog. How can I know which xml resource to load
int menuResourceId = getMenuResourceId();
// do the rest
}
public abstract int getMenuResourceId();
}