寫(xiě)了一個(gè)demo可以自動(dòng)顯示紅點(diǎn)塘辅,在其他界面紅點(diǎn)數(shù)變化彼棍,對(duì)應(yīng)的父界面的紅點(diǎn)也會(huì)發(fā)生變化。
如下圖:
設(shè)計(jì)思路:
每個(gè)紅點(diǎn)可視為為一個(gè)節(jié)點(diǎn)简卧,每個(gè)節(jié)點(diǎn)都可以作為父節(jié)點(diǎn)或子節(jié)點(diǎn),類似樹(shù)狀烤芦。與樹(shù)狀不一樣的是举娩,子節(jié)點(diǎn)可以有多個(gè)父節(jié)點(diǎn)(例如在一個(gè)子頁(yè)面里面的紅點(diǎn)有多個(gè)快捷入口紅點(diǎn))。
節(jié)點(diǎn)數(shù)據(jù)結(jié)構(gòu):
1.點(diǎn)數(shù)
2.子節(jié)點(diǎn)列表
3.父節(jié)點(diǎn)列表构罗。如下圖
實(shí)現(xiàn)算法:只有子節(jié)點(diǎn)可主動(dòng)設(shè)置數(shù)據(jù)變化铜涉,當(dāng)一個(gè)個(gè)子節(jié)點(diǎn)的數(shù)據(jù)發(fā)生變化,需要通知父節(jié)點(diǎn)重新計(jì)算點(diǎn)數(shù)遂唧,計(jì)算方法為將所有子節(jié)點(diǎn)點(diǎn)數(shù)相加芙代,然后遞歸觸發(fā)父節(jié)點(diǎn)計(jì)算方法,向上刷新數(shù)據(jù)盖彭。父節(jié)點(diǎn)可以做清零操作纹烹,即把所有子節(jié)點(diǎn)點(diǎn)數(shù)置0,向下遞歸清零召边,并且向上遞歸計(jì)算點(diǎn)數(shù)铺呵。下圖是一個(gè)例子
代碼例子:
其實(shí)只有兩個(gè)類
Reddot 為控制紅點(diǎn)的類,包含標(biāo)識(shí)key、紅點(diǎn)值掌实、父節(jié)點(diǎn)陪蜻、子節(jié)點(diǎn)、自動(dòng)計(jì)算通知更新接口等
ReddotManage 為維護(hù)Reddot的類
public class ReddotList {
public static ReddotmainReddot =new Reddot("mainReddot");
public static ReddotsecondReedot1 =new Reddot("secondReedot1",mainReddot);
public static ReddotsecondReedot2 =new Reddot("secondReedot2",mainReddot);
public static void init(){
secondReedot1.addOne();
secondReedot2.addOne();
}
}
數(shù)據(jù)需要再使用前初始化贱鼻、這里放在Application 這里了
public class DemoApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ReddotList.init();
}
}
Activity有兩個(gè)MainActivity 和 SecondActivity宴卖。MainActivty有個(gè)紅點(diǎn),改紅點(diǎn)數(shù)值為 SecondActivity的紅點(diǎn)數(shù)值總和
//注冊(cè)紅點(diǎn)監(jiān)聽(tīng)器
ReddotList.mainReddot.registerLisenter(this);
更新回調(diào)方法
@Override
public void updateView(String key, int count) {
if (key.equals(ReddotList.mainReddot.getKey())) {
mMainDot.setVisibility(count > 0 ? View.VISIBLE : View.GONE);
mMainDot.setText(count + "");
}
}
紅點(diǎn)點(diǎn)數(shù)變化方法邻悬,還有setValue等
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_left_add:
ReddotList.secondReedot1.addOne();
break;
case R.id.button_left_reduce:
ReddotList.secondReedot1.reduceOne();
break;
case R.id.button_right_add:
ReddotList.secondReedot2.addOne();
break;
case R.id.button_right_reduce:
ReddotList.secondReedot2.reduceOne();
break;
}
}
頁(yè)面被銷毀時(shí)候記得調(diào)用unRegister 或clearLinsenter 方法
@Override
protected void onDestroy() {
super.onDestroy();
ReddotManager.clearLinsenter(ReddotList.secondReedot1.getKey());
ReddotManager.clearLinsenter(ReddotList.secondReedot2.getKey());
}