2012-03-28 80 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