Android MVP + 娉涘瀷锛屽疄鐜颁簡鍙嬪ソVP浜や簰鍙夾ctivity娼滃湪鐨勫唴瀛樻硠闇茬殑浼樺寲

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android MVP + 娉涘瀷锛屽疄鐜颁簡鍙嬪ソVP浜や簰鍙夾ctivity娼滃湪鐨勫唴瀛樻硠闇茬殑浼樺寲相关的知识,希望对你有一定的参考价值。

鏍囩锛?/p>

銆€銆€Android MVP绮楁潵宸茬粡鏈夋鏃堕棿浜嗭紝鍦ㄩ」鐩腑鎴戜篃澶氬灏戝皯鐢ㄤ簡涓€浜涳紝涓嶅緱涓嶈浠g爜浣跨敤杩欑妯″紡鍚庯紝鏉′緥纭疄娓呮櫚浜嗗ソ澶氾紝鏁翠釜娴佺▼鐪嬭捣鏉ユ湁鐐瑰悇鍙稿叾鑱岀殑鎰熻(鍙︿竴绉嶇殑java闈㈠悜瀵硅薄鐨勬柟寮?銆?/span>

銆€銆€涓嶈繃杩欓噷鏄垜鍦ㄤ娇鐢ㄨ繃绋嬩腑閬囧埌鐨勪竴鐐瑰皬浼樺寲锛岀洿鎺ヨ繘鍏ヤ唬鐮佹潵璇村惂锛侊紒锛?/span>

 1 import java.lang.ref.Reference;
 2 import java.lang.ref.WeakReference;
 3 
 4 public class Presenter <T>{
 5 
 6     private Reference<T> mReference = null;
 7     
 8     public void onAttach(T view){
 9         mReference = new WeakReference<T>(view);
10     };
11     
12     public boolean isAttach(){
13         return null != mReference && null != mReference.get();
14     }
15     
16     public void onDettach(){
17         if(null != mReference){
18             mReference.clear();
19             mReference = null;
20         }
21     };
22 }

銆€銆€涓婅堪浠g爜鎴戣繖閲岀畝鍗曡涓嬶紝娉涘瀷鐨勫畾涔夋槸涓轰簡缁橝ctivity鍙婂叾瀛愮被澹版槑浣跨敤(涓哄暐杩欎箞璇达紝鍥犱负presenter鏄笓闂ㄩ拡瀵筕iew宸ヤ綔鐨勶紝浠栫殑瀹氫箟蹇呴』渚濊禆浜嶸iew鐨勫姛鑳芥潵瀹屾垚.),杩欓噷鍙互鐪嬪埌鎴戠畝鍗曟槸閲囩敤浜嗗急寮曠敤鐨勬柟寮忓幓鍙傛暟杩欎釜View鐨勫瀵硅薄寮曠敤,杩欓噷鎴戜富瑕佽€冭檻鍒颁竾涓€Activity涓嶈蛋onDestroy鏂规硶锛屼絾鏄▼搴忓嵈閫€鍑轰簡锛岀幇瀹炰腑杩欑鍙兘鎬у緢灏忥紝涓嶈繃纭疄鏄瓨鍦ㄧ殑锛屽急寮曠敤涓昏灏辨槸涓轰簡杩欎釜鐩殑鑰屽姞鐨勩€?/span>

 

銆€銆€绱ф帴鐫€涓€璧锋潵鐪婤aseActivity

 1 public abstract class BaseActivity<V, T extends Presenter<V>> extends Activity{
 2 
 3     protected T mPresenter;
 4     
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         mPresenter = createPresener();
 9         mPresenter.onAttach((V) this);
10     }
11 
12     
13     @Override
14     protected void onDestroy() {
15         // TODO Auto-generated method stub
16         super.onDestroy();
17         mPresenter.onDettach();
18     }
19     
20     protected abstract T createPresener();
21 }

銆€銆€杩欓噷鍙湅鍒帮紝杩欓噷鐢变簬鏄疊aseActivity锛屾垜甯屾湜浠栧幓鍋氱殑宸ヤ綔灏辨槸鍦ˋctivty鍒涘缓鐨勬椂鍊欏厛鍒涘缓Presenter瀵硅薄锛屽苟鍛婄煡Presenter鑷繁宸茬粡琚垱寤猴紝鍚屾椂灏嗚嚜韬敞鍏ョ粰Presenter锛屼互渚夸簬瀹屾垚P鍒癡鐨勫洖璋冨伐浣? T extent Presenter鏄负浜嗕繚璇乧reatePrenter杩斿洖鐨勪簨Presenter 鐨勫瓙绫诲璞? 8琛屾病鏈夊垽绌虹洿鎺ヤ娇鐢ㄧ殑鐩殑鏄负浜嗘洿濂界殑浣跨敤MVP鐨勬€濇兂锛屾墍浠ヨ繖閲岀殑鎶借薄鏂规硶鏄笉鍏佽杩斿洖null鐨勶紝杩欐槸鎴戠殑涓汉璁捐锛屼笉杩囧ぇ瀹惰鏄笇鏈涜繑鍥瀗ull锛屽彲浠ヨ嚜宸卞湪杩涗竴姝ョ殑鍧愪笅澶勭悊.

 

銆€銆€銆€涔嬩笂鐨勭畝鍗曠殑VP浜や簰锛屾垜鏄牴鎹釜浜洪渶姹傚仛鐨勫畾涔?Attach, Dettach, isAttach).

銆€銆€銆€

 

以上是关于Android MVP + 娉涘瀷锛屽疄鐜颁簡鍙嬪ソVP浜や簰鍙夾ctivity娼滃湪鐨勫唴瀛樻硠闇茬殑浼樺寲的主要内容,如果未能解决你的问题,请参考以下文章

椤电爜0~N 锛屽叾涓?锛?....9閮藉嚭鐜颁簡鍑犳

鏍规嵁榧犳爣绉诲叆绉诲嚭鏂瑰悜锛屽疄鐜癶over鏁堟灉

鏍规嵁 Promise/A+ 鍜?ES6 瑙勮寖锛屽疄鐜?Promise 婧愮爜锛堥檮璇︾粏娉ㄩ噴鍜屾祴璇曪級

VGG16杩佺Щ瀛︿範锛屽疄鐜板尰瀛﹀浘鍍忚瘑鍒垎绫诲伐绋嬮」鐩?/h1>

200琛孞S浠g爜锛屽甫浣犲疄鐜颁唬鐮佺紪璇戝櫒锛堜汉浜洪兘鑳藉浼氾級

銆怞S銆?200琛孞S浠g爜锛屽甫浣犲疄鐜颁唬鐮佺紪璇戝櫒锛堜汉浜洪兘鑳藉浼氾級