2012-03-28 38 views
1

以下代碼來自我的Android Mono應用程序的C#部分。它將最終成爲萬用表模擬器的GUI,但現在只是顯示文本。這是相當直接的:使用代表的Android Mono中的按鈕屏幕更改

- 點擊其中一個按鈕去那個儀表(電壓表,電流表,歐姆表) - 點擊「重新掃描」按鈕和TextView告訴你多少次你點擊那個按鈕。 - 點擊其中一個米按鈕或主頁按鈕來切換視圖

這麼多工作完美無缺。不幸的是,一旦我切換視圖,按鈕停止工作。以下是歐姆按鈕和Amp按鈕的代碼。歐姆按鈕是「完整的」按鈕,可以顯示所有其他屏幕的視圖。出於測試目的,我正在進入功放屏幕,但是當我去那裏時,其重新掃描按鈕什麼都不做。沒有任何按鈕可以做任何事情。

相當肯定的是,問題是我使用委託的命令,但沒有我的研究使我在向解決方案的任何方式。

如果需要,我可以提供更多的主代碼和XML代碼。

ampButton.Click += delegate 
      { 
       SetContentView(Resource.Layout.AmpScreen); 
       Button ampButtonData = FindViewById<Button>(Resource.Id.CurrentButtonamp); 
       TextView ampData = FindViewById<TextView>(Resource.Id.ampdata); 
       ampButtonData.Click += delegate 
       { 
        ampData.Text = string.Format("{0} clicks!", count2++); 
       }; 
       Button amp2volt = FindViewById<Button>(Resource.Id.Amp2VoltButton); 
       Button amp2ohm = FindViewById<Button>(Resource.Id.Amp2OhmButton); 
       Button amp2home = FindViewById<Button>(Resource.Id.Amp2HomeButton); 
      }; 


      ohmButton.Click += delegate 
      { 
       SetContentView(Resource.Layout.OhmScreen); 
       Button ohmButtonData = FindViewById<Button>(Resource.Id.CurrentButtonohm); 
       TextView ohmData = FindViewById<TextView>(Resource.Id.ohmdata); 
       ohmButtonData.Click += delegate 
       { 
        ohmData.Text = string.Format("{0} clicks!", count3++); 
       }; 

       Button ohm2amp = FindViewById<Button>(Resource.Id.Ohm2AmpButton); 
       Button ohm2volt = FindViewById<Button>(Resource.Id.Ohm2VoltButton); 
       Button ohm2home = FindViewById<Button>(Resource.Id.Ohm2HomeButton); 

       ohm2amp.Click += delegate 
       { 
        SetContentView(Resource.Layout.AmpScreen); 
       }; 

       ohm2volt.Click += delegate 
       { 
        SetContentView(Resource.Layout.VoltScreen); 
       }; 

       ohm2home.Click += delegate 
       { 
        SetContentView(Resource.Layout.Main); 
       }; 

      }; 

回答

0

我認爲你的問題是你每次都替換整個視圖 - 所以按鈕實例正在改變。

在SetContentView內部會發生什麼情況,InflatorService被要求基於傳入的XML創建一組全新的UI對象,現有的UI將被擦乾淨,然後這些新的UI對象被置於其位置。

新UI對象恰好與舊對象具有相同的資源標識符並不重要 - 它們仍然是單獨的實例。

如果您想繼續使用您當前的方法,那麼您需要在每個SetContentView之後重新連接所有事件 - 例如,

 ohm2amp.Click += delegate 
      { 
       SetContentView(Resource.Layout.AmpScreen); 
       RewireEvents(); 
      }; 

 private void RewireEvents() 
     { 
      var ohm2home = FindViewById<Button>(Resource.Id.ohm2home); 
      ohm2home.Click += { /* todo */ }; 
      // etc 
     } 

替代地,可能考慮不同的UI:

  • 例如您可以在不同的子佈局上更改「可見性」,而不是調用SetContentView來替換所有子元素的所有內容,例如
  • 或者你可以使用多個活動(或標籤),而不是單個活動

希望幫助

+0

非常感謝您斯圖爾特。 我提出了您的建議更改並實施了一些試驗性測試,並對他們的成功感到高興。我的整個GUI現在已經完成,完成了整個結構。 – Zach 2012-03-29 15:52:56