gpt4 book ai didi

android - "Broken OOP"或如何使用 NavigationDrawer 回调

转载 作者:行者123 更新时间:2023-11-30 02:08:59 25 4
gpt4 key购买 nike

我正在使用 NavigationDrawer 的自定义实现创建应用程序- MaterialDrawer .这是一个很棒的库,它使用动态添加抽屉到现有的 View 层次结构中。
至于我们需要 Navigation Drawer 出现在我们应用程序中的所有 Activity 中,我们可以有一个 BasicActivity 抽象类来初始化抽屉,设置它并做一些其他与所有 Activity 相似的基本事情.

这是我的 BaseActivity 的部分逻辑。

  @Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l, IDrawerItem iDrawerItem) {
Intent intent;
int itemId = iDrawerItem.getIdentifier();
if(itemId==getActivityTag()) {
return;
}
switch(itemId){
case DrawerConstants.PrimaryItemConstants.ALL_CATEGORIES_PAGE_INDEX:
intent = new Intent(this,CategoryListActivity.class);
startActivity(intent);
break;
case DrawerConstants.PrimaryItemConstants.LOGIN_ITEM_INDEX:
intent = new Intent(this,LoginScreen.class);
startActivity(intent);
break;
}
}
public abstract int getActivityTag();

一切似乎都很好,但一个问题是我们必须了解我们所有的子继承类并在语句中在它们之间切换。
所以 parent 知道它的 child 。
我认为就 OOP 而言这是不好的做法。
也许有任何解决方法可以按照设计模式以优雅的方式解决这个问题。

提前致谢。

最佳答案

您可以做的是在 DrawerConstants.PrimaryItemConstants 类中保留值的 Map,而不是使用 switch-case

class PrimaryItemConstants {

static private boolean didInit = false;
static public Map<Integer,Class> classMap = new HashMap<Integer,Class>();

/** initializes static variables, including classMap.
* Can be called multiple times but will only be initialized on first call.
*/
static public void initialize(){
if (didInit)return;
classMap.put(new Integer(ALL_CATEGORIES_PAGE_INDEX),CategoryListActivity.class);
classMap.put(new Integer(LOGIN_ITEM_INDEX), LoginScreen.class);
}

}

然后在您的 onItemClick 中,您将从 Map 获取类:

class BaseActivity {

/** starts the activity corresponding the the clicked IDrawerItem
*
*
* @throws Exception if itemId does not have a corresponding key in DrawerConstants.PrimaryItemConstants.classMap
*/
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l, IDrawerItem iDrawerItem) {
Intent intent;
int itemId = iDrawerItem.getIdentifier();
if(itemId==getActivityTag()) {
return;
}
DrawerConstants.PrimaryItemConstants.initialize();
if (DrawerConstants.PrimaryItemConstants.classMap.contains(new Integer(itemId)){
intent = new Intent(this,DrawerConstants.PrimaryItemConstants.classMap.get(new Integer(itemId));
startActivity(intent);
} else {
//or whatever you want
throw new Exception("itemId "+itemId+" not found in classMap");
}
}
}

关于android - "Broken OOP"或如何使用 NavigationDrawer 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30373306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com