【问题标题】:using Composition in c# android activity to access the data在 c# android 活动中使用 Composition 来访问数据
【发布时间】:2014-07-30 17:26:58
【问题描述】:

我正在开发一个 android 应用程序并使用 IDE Xamarin 工作室。我有两个活动类,在第一个活动类中执行一些函数并返回值。这些值应该在另一个类(我的意思是第二个活动类)中访问。我通常只是在第二个活动类中创建第一个活动类的实例并尝试访问这些值。但我认为这是一个错误,因为 Xamarin Studio 没有在自动完成列表中显示变量名称。

第一个活动类:

public class getInformation : Activity
    {
        public string SourceText, DestText;
        public string[] source, destination;
        public int numval;

        public getInformation() { }

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            SetContentView (Resource.Layout.getInformation_activity);

            /* some fields and buttons go here

             */

            Button.Click += delegate{ //some extra code goes here...
                StartActivity(typeof(DisplayInformation));

                source = SourceText.Split(new String[]{','});
                destination = DestText.Split(new String[]{','});

                numval = Convert.ToInt32(source[0]);
            };

        }           
    }

在这里,我试图访问变量 String[] source 和 int numval。

第二个活动在这里:

public class DisplayInformation : Activity
    {
        public getInformation getaddress = new getInformation (); 
                                                    //instance of first class created.

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);
            SetContentView (Resource.Layout.displayInformation_Activity);

             //button click event not necessary mentioning here.
        }
       getaddress.numval;
                   // here it shows error, i mean it doesn't show numval in autocomplete.
    }

现在,我的问题是我想通过在第二个类(活动)中为第一个类创建一个实例来访问值 source[0]、source[1] 和 numval。有什么方法可以访问数据。

如果我的代码中有任何错误,请原谅我并更正我的答案。

【问题讨论】:

  • 问题已解决 - 谢谢..

标签: c# android list android-activity xamarin


【解决方案1】:

如果您从 FirstActivity 创建 SecondActivity,最好在 SecondActivity 中设置来自 FirstActivity 的信息,反之亦然。

这样,当 SecondActivity 来尝试从 FirstActivity 检索数据时,您可以确保这两个 Activity 实际上仍然存在。

(至少)有两种方法可以做到这一点。

选项 1 将数据存储在 Intent 中并使用该 Intent 启动 SecondActvity。 http://developer.xamarin.com/recipes/android/fundamentals/activity/pass_data_between_activity/

选项 2

var secondActivity = StartActivity(typeof(SecondActivity));
secondActivity.SetMyData(data);

【讨论】:

  • 谢谢它的工作。以前,我将变量定义为静态(对全局变量),这是一个很大的错误。但是您的解决方案看起来很完美。
猜你喜欢
  • 1970-01-01
  • 2014-01-18
  • 2012-08-10
  • 1970-01-01
  • 2017-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多